OOP Java Ita
OOP Java Ita
oggetti 2013
Giorgio Bruno
JDK http://www.oracle.com/technetwork/java/javase/downloads/index.html
package testG;
import g.*;
public class TestPoint0a {
public static void main(String[] args) {
Point0a p = new Point0a(10,20);
p.move(100, 200);
System.out.println(p); // x = 100 y = 200
}
}
G. Bruno Programmazione a oggetti 5
classe Point0
package g;
public class Point0 {
private int x,y;
public Point0 (int a, int b) {x = a; y = b;}
public void move (int a, int b) {x = a; y = b;}
public String toString () {return "x = " + x + " y = " + y;}
public static void main (String[] args) {
Point0 p = new Point0(10,20);
p.move(100, 200);
System.out.println(p); // x = 100 y = 200
}
}
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); //Display the string.
}
}
?: op1 ? op2 : op3 If op1 is true, returns op2. Otherwise, returns op3.
[] type [] Declares an array of unknown length, which contains type
elements.
[] type[op1] Creates an array with op1 elements. Must be used with the new operator.
[] op1[op2] Accesses the element at op2 index within the array op1. Indices begin at 0.
package graphics;
import graphics.*;
The following chart shows the access level permitted by each specifier.
Specifier class subclass package world
private X
protected X X X
public X X X X
(package) X X
intValue Integer.parseInt
Integer
String
String Integer,
toString Integer.valueOf
//populate matrix
for (int i = 0; i < aMatrix.length; i++) {
aMatrix[i] = new int[5]; //create sub-array
for (int j = 0; j < aMatrix[i].length; j++) {
aMatrix[i][j] = i + j;
}
You must specify the length of the primary array when you
create the array. You can leave the length of the sub-arrays
unspecified until you create them.
package g;
public class Particle extends Point {
private int m;
public int getM() {return m;}
public void setM(int m) {this.m = m;}
public Particle(int x, int y, int m) {super(x,y); this.m = m;}
public String toString(){return super.toString() + " m = " + m;}
}
Note
La prima istruzione del costruttore di Particle deve essere la chiamata di
un costruttore della classe di base.
Le propriet della classe di base non private sono accessibili mediante il
rif. super.
IsA IsA
Cerchio Rettangolo
package g;
public interface Movable {
void move(int x, int y);
}
public class Point implements Movable {
public class Rectangle implements Movable {
Risultato: 90
RuntimeException:
il compilatore non
forza il catch
catch (Exception e) {
try{
System.out.println("Caught exception " + e.getMessage());
int total = 0; int correct = 10;
int n = correct/total;}
catch (Exception f){
System.out.println("Caught exception B " +
f.getMessage());}
}}
Method Summary
protected Object clone()
Creates and returns a copy of this object.
boolean equals(Object obj)
Indicates whether some other object is "equal to" this one.
protected void finalize()
Called by the garbage collector on an object when garbage collection determines
that there are no more references to the object.
Class<?> getClass()
Returns the runtime class of this Object.
int hashCode()
Returns a hash code value for the object.
void notify()
Wakes up a single thread that is waiting on this object's monitor.
void notifyAll()
Wakes up all threads that are waiting on this object's monitor.
String toString()
Returns a string representation of the object.
void wait()
Causes the current thread to wait until another thread invokes the notify() method or
the notifyAll() method for this object.
void wait(long timeout)
Causes the current thread to wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has
elapsed.
void wait(long timeout, int nanos)
Causes the current thread to wait until another thread invokes the notify() method or
the notifyAll() method for this object, or some other thread interrupts the current thread,
or a certain amount of real time has elapsed.
G. Bruno Programmazione a oggetti 92
equals
package g;
public class Point {
private int x,y;
public int getX() {return x;}
public int getY() {return y;}
public Point(int x, int y) {this.x = x; this.y = y;}
public void move(int x, int y) {this.x = x; this.y = y;}
public String toString(){return "x = " + x + " y = " + y;}
public boolean equals (Object o) {
if (!(o instanceof Point)) return false;
Point p = (Point)o; return this.x == p.x && this.y == p.y;}
public boolean isEqualTo(Point p) {
return this.x == p.x && this.y == p.y;}}
Output: caffein
boolean hasMoreElements()
Tests if this enumeration contains more elements.
E nextElement()
Returns the next element of this enumeration if this enumeration
object has at least one more element to provide.
Collection Iterator,
ListIterator
G. Bruno Programmazione a oggetti 116
Collections
The two general purpose Set implementations are HashSet and TreeSet. It's very
straightforward to decide which of these two to use. HashSet is much faster
(constant time vs. log time for most operations), but offers no ordering
guarantees. If you need to use the operations in the SortedSet, or in-order
iteration is important to you, use TreeSet. Otherwise, use HashSet.
The two general purpose List implementations are ArrayList and LinkedList.
Most of the time, you'll probably use ArrayList. It offers constant time positional
access, and it's just plain fast, because it does not have to allocate a node object
for each element in the List, and it can take advantage of the native method
System.arraycopy when it has to move multiple elements at once. Think of
ArrayList as Vector without the synchronization overhead. ArrayList has one
tuning parameter, the initial capacity.
The two general purpose Map implementations are HashMap and TreeMap. The
situation for Map is exactly analogous to Set. If you need SortedMap operations
or in-order Collection-view iteration, go for TreeMap; otherwise, go for HashMap.
Everything else in the Set section also applies to Map so just re-read it.
int compareTo(T o)
Compares this object with the specified object for order. Returns a negative
integer, zero, or a positive integer as this object is less than, equal to, or greater
than the specified object.
LinkedList()
Constructs an empty list.
LinkedList(Collection<? extends E> c)
Constructs a list containing the elements of the specified collection,
in the order they are returned by the collection's iterator.
Searching
The binarySearch algorithm searches for a specified element in a sorted List
using the binary search algorithm.
The following idiom, usable with both forms of the binarySearch operation, looks
for the specified search key, and inserts it at the appropriate position if it's not
already present:
int pos = Collections.binarySearch(l, key);
if (pos < 0)
l.add(-pos-1, key);
Uso di Random
Random randGen = new Random();
// intero casuale tra 0 e 99
int i = Math.abs(randGen.nextInt())%100;
a|
b|
c| il token non contiene il
d | delimitatore
Suppose you want to add data and behavior to an enum. For example
consider the planets of the solar system. Each planet knows its mass and
radius, and can calculate its surface gravity and the weight of an object
on the planet. Here is how it looks:
Architectural Patterns
An architectural pattern expresses a fundamental structural organization or
schema for software systems. It provides a set of predefined subsystems,
specifies their responsibilities, and includes rules and guidelines for
organizing the relationships between them.
Design Patterns
A design pattern provides a scheme for refining the subsystems or
components of a software system, or the relationships between them. It
describes commonly recurring structure of communicating components that
solves a general design problem within a particular context.
Idioms
An idiom is a low-level pattern specific to a programming language. An
idiom describes how to implement particular aspects of components or the
relationships between them using the features of the given language.
<<interface>> <<interface>>
Agenzia Abbonato
void addAbbonato (Abbonato a); void riceviNotizia(Notizia nt);
Persona
Notizia
usage
Azienda
implementation NotiziaSportiva
inheritance
package abbonamenti;
public interface Agenzia {
void addAbbonato (Abbonato a);
}
package abbonamenti;
public class NotiziaSportiva extends Notizia {
public NotiziaSportiva(String contenuto, String dettagli) {
super(contenuto); this.dettagli = dettagli;}
}
package abbonamenti;
public class Azienda extends Persona{
public Azienda(String name, Agenzia... agenzie) {
super(name, agenzie);
}}
IOException
readLine
BufferedReader PrintWriter caratteri - testo
Event-driven programming
java.awt.event
Class ActionEvent
String getActionCommand()
Returns the command string associated with this action.
int getModifiers()
Returns the modifier keys held down during this action event.
long getWhen()
Returns the timestamp of when this event occurred.
String paramString()
Returns a parameter string identifying this action event.
Layout management is the process of determining the size and position of components.
By default, each container has a layout manager -- an object that performs layout
management for the components within the container. The Java platform supplies five
commonly used layout managers: BorderLayout, BoxLayout, FlowLayout,
GridBagLayout, and GridLayout.
User clicks a button, presses Return while typing in a text field, or chooses a menu item ActionListener
User presses a mouse button while the cursor is over a component MouseListener
Caption: When the user clicks a button, the button's action listeners are
notified.
EsempiGUI Previsioni
Esempio
LineApplet1
LineThread
in EsempiGUI
From http://developer.android.com/training/
All user interface elements in an Android app are built using View and
ViewGroup objects. A View is an object that draws something on the
screen that the user can interact with. A ViewGroup is an object that
holds other View (and ViewGroup) objects in order to define the layout of
the interface.
valore
pulsante +
pulsante Reset counter
classe faade
factory methods
strutture dati con mappe
Textbook on UML:
M. Fowler, UML distilled, Addison-Wesley.
Domain model may also be called class models and information models.
Domain model: high level (conceptual, business) perspective
Class model: technical (implementation) perspective
Information model: data base perspective
Professor Course
teaches
enrolledIn
1 1..3
Professor Course
teaches
+
enrolledIn
10..50
Student
1 1..3
Professor Course
Indicator Meaning
teaches
0..1 Zero or one
1 One only
Book
1
Loan *
Book
1
Loan
1 *
An order is made up of order
Product OrderLine lines; each order line refers to
+ a product and includes the
number of units required.
Order
Attributes:
OrderLine: int n.
class
{abstract} 1 {abstract}
model
Vehicle Owner
Student
1. Programming-oriented perspective
The class model represents an object-oriented program (e.g. a java
program): the model classes are mapped to java classes, the attributes of
the model classes are mapped to the attributes of the java classes,
inheritance relationships are mapped to extend relationships between
java classes, and the other relationships are mapped to single references
or collections in the java classes.
Suggerimento
In ogni oggetto Competenza si registrino il n. di attivit che la richiedono
e il n. di utenti che la possiedono.
Eccezioni: competenza ripetuta/inesistente, idem per attivit e utente
HM(nome)
associazione
HM = HashMap Competenza
toS
Attributi:
Competenza: String nome, int nA, int nU.
Attivit: String nome, TreeSet<String> competenze.
Utente: String nome, TreeSet<String> competenze.
package competenze;
import java.util.*;
public class Utente {
private String nome; private TreeSet<String> competenze;
Utente(String nome, TreeSet<String> competenze) {
this.nome = nome; this.competenze = competenze;}
public String toString(){return nome + competenze;}}
Competenza
TS TS
toS
HM = HashMap
TS = TreeSet
Attributi: associazione
Competenza: String nome.
Attivit: String nome. associazione bidirezionale m,n
Utente: String nome.
import java.util.*;
public class Competenze {
private Map<String,Competenza> competenze = new HashMap<String,Competenza>();
private Map<String,Attivit> attivit = new HashMap<String,Attivit>();
private Map<String,Utente> utenti = new HashMap<String,Utente>();
public void newCompetenza (String nome) throws CompEccezione {
if (competenze.containsKey(nome)) throw new CompEccezione("competenza duplicata:" + nome);
Competenza c = new Competenza(nome); competenze.put(nome, c);}
privateTreeSet<Competenza> getCompetenze (String[] v) throws CompEccezione {
TreeSet<Competenza> s = new TreeSet<Competenza>();
for (String c:v){
Competenza comp = competenze.get(c);
if (comp == null) throw new CompEccezione("competenza inesistente:" + c);
else if (!s.add(comp)) throw new CompEccezione("competenza duplicata:" + c);
}
return s;}
public void newAttivit (String nome, String... v) throws CompEccezione {
if (attivit.containsKey(nome)) throw new CompEccezione("attivit duplicata:" + nome);
Attivit a = new Attivit(nome); attivit.put(nome, a);
for (Competenza c: getCompetenze (v)) {a.addCompetenza(c); c.addAttivit(a);}
}
Attributi
Libro: String titolo, int nVolumi, int nPrestiti.
Volume: int codice, Libro libro.
Utente: String nome, int maxVolumi.
Attributi
Aereo: String codiceAereo, String descrizione, int numeroPosti.
Volo: String codiceVolo, String luogoPartenza, String luogoArrivo, int
oraPartenza, int oraArrivo.
VoloGiornaliero: int giorno, TreeSet(String) prenotazioni.
R1 - Ricercatori
L'interazione con il sistema avviene tramite la classe Valutazione.
possibile inserire i dati di un nuovo ricercatore tramite il metodo addRicercatore() che
riceve come parametri un codice univoco, nome e cognome; il metodo restituisce un oggetto
di tipo Ricercatore.
La classe Ricercatore permette di conoscere codice, nome e cognome tramite i metodi
getCodice(), getFirst() e getLast(). Per ottenere uno specifico ricercatore si usa il
metodo getRicercatore().
R2 - Riviste
Per inserire delle riviste nel sistema si utilizza il metodo addRivista() che riceve come
parametri il codice ISSN, il nome (titolo) della rivista e l'Impact Factor, che un indice che
rappresenta la bont della rivista. Il metodo restituisce un oggetto di classe Rivista, la
quale offre i metodi getTitolo() e getIF() per accedere al titolo e all'Impact Factor della
rivista.
Per poter ottenere una rivista specifica si utilizza il metodo getRivista() che riceve come
parametro il codice ISSN. Il metodo getRiviste() restituisce la lista delle riviste in ordine
di Impact Factor decrescente.
v = new Valutazione();
v.leggi("dati");
for (Rivista r: v.getRiviste()) System.out.println(r.getTitolo() + " " + r.getIF());
ae = v.getRicercatore("123");
System.out.println(ae.getLast() + " ha pubblicato " + ae.numArticoli());
System.out.println(ae.getLast() + " ha h-index " + ae.hIndex());}}
AL = ArrayList
HM = HashMap