Oop
Oop
Oop
http://www.omg.org/
to be user friendly
to provide appropriate
response and processing time
to be in a failure-free
condition at all times
to perform appropriately, relative
to the amount of resources used
to be easily and transparently
upgradable
to have consideration for future
growth
Reusability
availability of off-the shelf components
• reduced time-to-market
• improved reliability
Extensibility
possibility of adding functionalities
• increased life cycle duration
Flexibility
changes in one component do not affect other components
• reduced cost of maintenance
6
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOP: Modelling
Class
software representation of an abstraction
it separates the (private) implementation of data and methods from the
(public) declaration of behavior (encapsulation, information hiding)
8
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOP: Objects
Object
an instance of a class, from which it gets:
• the implementation of data and methods
• the public (externally visible) parts
9
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOP: creation of objects from a class
14
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JT: Development environment
Java bytecodes
platform-independent intermediate language
Java Virtual Machine (Java VM)
virtual machine able to execute Java bytecodes
15
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JT: Portability
Check of correctness of
parameter types and
compliance with access
rules
17
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JT: Java Platform
18
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JT: Java Platform, Standard Edition
19
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JDK Tools
javac
The compiler for the Java programming language.
java
The launcher for Java applications.
javadoc
API documentation generator.
appletviewer
Run and debug applets without a web browser.
jar
Manage Java Archive (JAR) files.
jdb
The Java Debugger.
javah
C header and stub generator. Used to write native methods.
javap
Class file disassembler
extcheck
Utility to detect Jar conflicts. 20
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JT: program example
21
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JT: BlueJ development environment
http://www.bluej.org/
22
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JT: Eclipse development environment
http://www.eclipse.org/ http://www.omondo.com/ 23
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
C: Class declaration
Methods • Methods
} • implement the behavior of
each object in the class
24
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
C: Access modifiers
25
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
C: Fields
public class TicketMachine
// A model of ticket machine that issues flat fare tickets
{
private int price;
// The price of a ticket from this machine.
private int balance;
// The amount of money entered by a customer so far.
private int total;
// The total amount of money collected by this machine.
Fields omitted
// Create a machine that issues tickets of the given price.
public TicketMachine(int ticketCost)
{
price = ticketCost;
balance = 0;
total = 0;
}
Methods omitted
}
Fields omitted
Constructors omitted
// Receive an amount of money from a customer. Check that it is sensible.
public void insertMoney(int amount)
{
if(amount > 0) {
balance += amount;
}
else {
System.out.println("Use a positive amount: " + amount);
}
}
}
Fields omitted
Constructors omitted
/* Return the money in the balance.
* The balance is cleared. */
public int refundBalance()
{
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
}
11:03
A display for a digital clock
30
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
O: Object interaction (2)
public class NumberDisplay
{
private int limit; // the maximum value
private int value; // the current value
// Constructor for NumberDisplay objects
public NumberDisplay(int rollOverLimit)
{
limit = rollOverLimit;
value = 0;
}
// Increment the display value by one, rolling to zero if the limit is reached.
public void increment()
{
value = (value + 1) % limit;
}
31
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
O: Object interaction (3)
32
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
O: Object creation
public class ClockDisplay
{
private NumberDisplay hours;
private NumberDisplay minutes;
private String displayString; // simulates the actual display
// Constructor for ClockDisplay objects.
public ClockDisplay(int hour, int minute)
{
hours = new NumberDisplay(24);
minutes = new NumberDisplay(60);
setTime(hour, minute); // report time on the actual display
}
} // end of class ClockDisplay
34
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
O: Method calls
public class ClockDisplay
{
// This method makes the clock display go one minute forward.
public void timeTick()
{
minutes.increment();
if(minutes.getValue() == 0) { // it just rolled over!
hours.increment();
}
updateDisplay();
}
// Update the internal string that represents the display.
private void updateDisplay()
{
displayString = hours.getDisplayValue() + ":" +
minutes.getDisplayValue();
}
}
35
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
O: Internal and external calls
37
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
O: Array (2)
public class LogAnalyzer
{
private int[] hourCounts;
private LogfileReader reader;
public LogAnalyzer()
{
hourCounts = new int[24];
reader = new LogfileReader();
}
public void analyzeHourlyData() public void printHourlyCounts()
{ {
while(reader.hasMoreEntries()) { System.out.println("Hr: Count");
LogEntry entry = reader.nextEntry(); for(int hour = 0; hour < hourCounts.length; hour++) {
int hour = entry.getHour(); System.out.println(hour + ": " + hourCounts[hour]);
hourCounts[hour]++; }
} }
} }
39
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
O: The library class ArrayList
java.util
public class ArrayList
Resizable-array implementation of the List interface. Implements
all optional list operations, and permits all elements, including
null. In addition to implementing the List interface, this class
provides methods to manipulate the size of the array that is used
internally to store the list. (This class is roughly equivalent to
Vector, except that it is unsynchronized.)
The size, isEmpty, get, set, iterator, and listIterator operations run
in constant time. The add operation runs in amortized constant
time, that is, adding n elements requires O(n) time. All of the
other operations run in linear time (roughly speaking). The
constant factor is low compared to that for the LinkedList
implementation.
Each ArrayList instance has a capacity. The capacity is the size
of the array used to store the elements in the list. It is always at
least as large as the list size. As elements are added an ArrayList,
its capacity grows automatically. The details of the growth policy
are not specified beyond the fact that adding an element has
constant amortized time cost.
An application can increase the capacity of an ArrayList instance
before adding a large number of elements using the
ensureCapacity operation. This may reduce the amount of
incremental reallocation.
40
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
O: ArrayList (1)
import java.util.ArrayList;
// A class to maintain an arbitrarily long list of notes.
public class Notebook
{
// Storage for an arbitrary number of notes.
private ArrayList notes;
// Perform any initialization that is required for the notebook.
public Notebook()
{
notes = new ArrayList();
}
// Store a new note into the notebook.
public void storeNote(String note)
{
notes.add(note);
}
// Return the number of notes currently in the notebook.
public int numberOfNotes()
{
return notes.size();
}
}
41
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
O: ArrayList (2)
public class Notebook
{
// List all notes in the notebook.
public void listNotes()
{
int index = 0;
while(index < notes.size()) {
System.out.println(notes.get(index));
index++;
}
}
// Remove a note from the notebook if it exists.
public void removeNote(int noteNumber)
{
if(noteNumber < 0) {}
else if(noteNumber < numberOfNotes()) {
notes.remove(noteNumber);
}
else {}
}
}
42
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
O: The library interface Iterator
import java.util.Iterator;
java.util
public interface Iterator
public class Notebook
An iterator over a collection. {
Iterators allow the caller to remove elements from the underlying // List all notes in the notebook.
collection during the iteration with well-defined semantics.
public void listNotes()
{
Iterator it = notes.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
43
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
O: Class (static) variables (1)
public class BouncingBall
{
private static final int gravity = 3;
private int ballDegradation = 2;
private Ellipse2D.Double circle;
private Color color;
private int diameter;
private int xPosition;
private int yPosition;
private final int groundPosition;
private Canvas canvas;
private int ySpeed = 1;
. . .
the final keyword Constructors and Methods omitted
declares a constant . . .
}
44
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
O: Class (static) variables (2)
the class (or static) variables are stored inside a class
instead of an object
the class variables are shared among all the objects in
the class
45
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
O: Class (static) methods
the class (or static) methods are directly called upon a class
ClassName.methodName (parameter-list)
a class method can only:
- access class variables
- invoke class methods
the Prompt command java HelloWorldApp invokes the class
method main from class HelloWorldApp
the out variable is a class variable of the class System
public class HelloWorldApp
{
public static void main( String[] args )
{
System.out.println("Hello World!" );
}
}
46
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
Class Design: Coupling and Cohesion
Coupling
degree of connectivity among classes
• loosely coupled system
• every class is mostly unrelated to other classes and communicates with
them through a small, well defined interface
• changes in one class do not affect other classes
Cohesion
degree of agreement between activities/entities and units of
code (methods, classes, packages)
• highly cohesive system
• each unit of code is responsible of a well identified activity/entity
• a unit of code can be used in different contexts (reusability)
47
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
CD: Coupling and Cohesion
48
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
CD: an adventure game project
"World of Zuul" is a very simple, text The CommandWords class is used to
based adventure game. recognize commands as they are typed in; it
holds an enumeration of all command words
Users can walk around some scenery.
known to the game.
The Parser class reads user input and tries to
interpret it as an "Adventure" command. It
returns the command as an object of class
Command.
The Command class holds information about
a command, consisting of two strings: a
command word and a second word.
The Room class represents one location in
the scenery of the game, connected to other
rooms via exits.
The Game class creates and initializes all
the others. It also evaluates and executes the
commands that the parser returns.
49
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
CD: Code duplication (1)
Code duplication is an indicator of bad design
It can cause inconsistency
It is usually a symptom of bad cohesion
Example:
both the methods printWelcome and goRoom in class Game
contain the following code:
55
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
CD: Method cohesion
each method should be responsible for a single activity
Example:
in class Game the opening text is not directly implemented by the method
play, but it is entrusted to the method printWelcome
public void play()
{
printWelcome();
boolean finished = false;
while (! finished) {
Command command = parser.getCommand();
finished = processCommand(command);
}
System.out.println("Thank you for playing. Good bye.");
}
private void printWelcome()
{
System.out.println("Welcome to Adventure!");
System.out.println("Type 'help' if you need help.");
printLocationInfo();
}
56
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
CD: Class cohesion
57
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
Inheritance: Superclass and subclass
a class can have subclasses (specializations) and/or
superclasses (generalizations)
each subclass inherits both the variables and the methods
from its superclass
58
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
I: a multimedia catalogue (1)
A database of multimedia entertainment application
• it allows to store information about CDs and videos.
• it provides enter, search, delete and print functions.
59
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
I: a multimedia catalogue (2)
...
...
60
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
I: a multimedia catalogue (3)
the new class Item is a generalization of CD and Video and
contains everything these two have in common
the classes CD e Video inherit all the elements declared in Item
and contain only declarations of the extra details
61
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
I: Subclasses in Java
the declaration class C1 extends C2 defines C1 as a
subclass of C2
the inherited elements have the same access rights
(private/public) of those declared in the superclass
public class CD extends Item
65
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: Type loss, casting and wrapper classes
the method get(int index) returns the element at position index in
an ArrayList
since the returned element has type Object, it cannot be directly
assigned to variables of different types (all subtypes of Object)
the type loss problem can be solved by explicitly indicating the
element type (casting)
example:
• if myList is an ArrayList containing a String object at position 5 , it is
possible to assign it to variable s1 in this way:
String s1 = (String)myList.get(5);
in Java the primitive types (byte, int, float, char, …) are not object
types, so they cannot be entered into a collection of objects
Java’s solution to this problem is wrapper classes : every primitive
type has a corresponding wrapper class (Byte, Integer, Float,
Character, …) that represents the same type, but is a real object
type
66
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: static type and dynamic type
static type
the type of a variable as declared in the source code
dynamic type
the type of the object currently stored in a variable
Video v1
Video v1 = new Video();
:Video
Item v2
Item v2 = new Video();
:Video
67
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: Overriding
a subclass may redefine (override) the implementation (body) of a
method declared in one of its superclasses
public class Item
{ . . .
public void print()
{
System.out.print("title: " + title + " (" + playingTime + " mins)");
if(gotIt) { System.out.println("*");} else { System.out.println();}
System.out.println(" " + comment);
}
}
69
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: Method polymorphism
Item i1
Item i1 = new Item();
:Item
i1.print();
Item i1
i1 = new Video();
i1.print(); :Video
70
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: the Object method toString
the universal superclass Object implements the method:
String toString()
Returns a string representation of the object
73
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: Abstract Classes and Methods
an abstract class is a class not intended for creating instances,
whose purpose is to serve as a superclass of other classes
an abstract class may contain abstract methods, which define a
signature without implementation (body)
a subclass of an abstract class is concrete (non abstract) only if
it provides implementations for all inherited abstract methods
in Java abstract classes and methods are declared by means of
the prefix key word abstract
Shape
Point
Circle
Cylinder
75
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (2)
76
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (3)
1 // Shape.java
2 // Shape abstract-superclass declaration.
3
4 public abstract class Shape {
5
6 // return area of shape; 0.0 by default
7 public double getArea()
8 {
9 return 0.0;
10 }
11
12 // return volume of shape; 0.0 by default
13 public double getVolume()
14 {
15 return 0.0;
16 }
17
18 // abstract method, overridden by subclasses
19 public abstract String getName();
20
21 } // end abstract class Shape
77
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (4)
1 // Point.java
2 // Point class declaration inherits from Shape.
3
4 public class Point extends Shape {
5 private int x; // x part of coordinate pair
6 private int y; // y part of coordinate pair
7
8 // no-argument constructor; x and y default to 0
9 public Point()
10 {
11 // implicit call to Object constructor occurs here
12 }
13
15 public Point( int xValue, int yValue )
16 {
17 // implicit call to Object constructor occurs here
18 x = xValue; // no need for validation
19 y = yValue; // no need for validation
20 }
21
22 // set x in coordinate pair
23 public void setX( int xValue )
24 {
25 x = xValue; // no need for validation
26 } 78
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (5)
29 public int getX()
30 {
31 return x;
32 }
35 public void setY( int yValue )
36 {
37 y = yValue; // no need for validation
38 }
41 public int getY()
42 {
43 return y;
44 }
45
46 // override abstract method getName to return "Point"
47 public String getName()
48 { Override
49 return "Point"; abstract
50 }
method getName.
51
52 // override toString to return String representation of Point
53 public String toString()
54 {
55 return "[" + getX() + ", " + getY() + "]";
56 }
58 } // end class Point 79
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (6)
1 // Circle.java
2 // Circle class inherits from Point.
3
4 public class Circle extends Point {
5 private double radius; // Circle's radius
6
7 // no-argument constructor; radius defaults to 0.0
8 public Circle()
9 {
10 // implicit call to Point constructor occurs here
11 }
12
13 // constructor
14 public Circle( int x, int y, double radiusValue )
15 {
16 super( x, y ); // call Point constructor
17 setRadius( radiusValue );
18 }
19
20 // set radius
21 public void setRadius( double radiusValue )
22 {
23 radius = ( radiusValue < 0.0 ? 0.0 : radiusValue );
24 }
80
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (7)
26 // return radius
27 public double getRadius()
28 {
29 return radius;
30 }
31
32 // calculate and return diameter
33 public double getDiameter()
34 {
35 return 2 * getRadius();
36 }
37
38 // calculate and return circumference
39 public double getCircumference()
40 {
41 return Math.PI * getDiameter();
42 }
43
44 // override method getArea to return Circle area Override method
45 public double getArea() getArea to
46 { return circle area
47 return Math.PI * getRadius() * getRadius();
48 }
49
81
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (8)
82
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (9)
1 // Cylinder.java
2 // Cylinder class inherits from Circle.
3
4 public class Cylinder extends Circle {
5 private double height; // Cylinder's height
6
7 // no-argument constructor; height defaults to 0.0
8 public Cylinder()
9 {
10 // implicit call to Circle constructor occurs here
11 }
12
13 // constructor
14 public Cylinder( int x, int y, double radius, double heightValue )
15 {
16 super( x, y, radius ); // call Circle constructor
17 setHeight( heightValue );
18 }
19
20 // set Cylinder's height
21 public void setHeight( double heightValue )
22 {
23 height = ( heightValue < 0.0 ? 0.0 : heightValue );
24 }
25 83
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (10)
26 // get Cylinder's height
27 public double getHeight()
28 {
29 return height;
30 }
Override method
31
getArea to
32 // override abstract method getArea to return Cylinder area
33 public double getArea()
return cylinder
34 { area
35 return 2 * super.getArea() + getCircumference() * getHeight();
36 }
37
38 // override abstract method getVolume to return Cylinder volume
39 public double getVolume()
Override method
40 {
getVolume to
41 return super.getArea() * getHeight();
42 } return cylinder
43 volume
44 // override abstract method getName to return "Cylinder"
45 public String getName()
46 { Override
47 return "Cylinder"; abstract
48 } method getName
84
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (11)
49
50 // override toString to return String representation of Cylinder
51 public String toString()
52 {
53 return super.toString() + "; Height = " + getHeight();
54 }
55
56 } // end class Cylinder
85
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (12)
1 // AbstractInheritanceTest.java
2 // Driver for shape, point, circle, cylinder hierarchy.
3 import java.text.DecimalFormat;
4 import javax.swing.JOptionPane;
5
6 public class AbstractInheritanceTest {
7
8 public static void main( String args[] )
9 {
10 // set floating-point number format
11 DecimalFormat twoDigits = new DecimalFormat( "0.00" );
12
13 // create Point, Circle and Cylinder objects
14 Point point = new Point( 7, 11 );
15 Circle circle = new Circle( 22, 8, 3.5 );
16 Cylinder cylinder = new Cylinder( 20, 30, 3.3, 10.75 );
17
18 // obtain name and string representation of each object
19 String output = point.getName() + ": " + point + "\n" +
20 circle.getName() + ": " + circle + "\n" +
21 cylinder.getName() + ": " + cylinder + "\n";
22
23 Shape arrayOfShapes[] = new Shape[ 3 ]; // create Shape array
24
86
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (13)
25 // aim arrayOfShapes[ 0 ] at subclass Point object
26 arrayOfShapes[ 0 ] = point;
27
28 // aim arrayOfShapes[ 1 ] at subclass Circle object
29 arrayOfShapes[ 1 ] = circle;
30
31 // aim arrayOfShapes[ 2 ] at subclass Cylinder object
32 arrayOfShapes[ 2 ] = cylinder;
33
34 // loop through arrayOfShapes to get name, string
35 // representation, area and volume of every Shape in array
36 for ( int i = 0; i < arrayOfShapes.length; i++ ) {
37 output += "\n\n" + arrayOfShapes[ i ].getName() + ": " +
38 arrayOfShapes[ i ].toString() + "\nArea = " +
39 twoDigits.format( arrayOfShapes[ i ].getArea() ) +
40 "\nVolume = " +
41 twoDigits.format( arrayOfShapes[ i ].getVolume() );
42 }
43
44 JOptionPane.showMessageDialog( null, output ); // display output
45
46 System.exit( 0 );
47
48 } // end main
50 } // end class AbstractInheritanceTest 87
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (14)
88
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (1)
89
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (2)
Employee
BasePlusCommissionEmployee
Superclass Employee
Abstract method earnings (returns pay)
• abstract because need to know employee type
• cannot calculate for generic employee
90
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (3)
91
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (4)
1 // Employee.java
2 // Employee abstract superclass.
3
4 public abstract class Employee {
Declares class Employee
5 private String firstName; as abstract class.
6 private String lastName;
7 private String socialSecurityNumber;
8
9 // constructor
10 public Employee( String first, String last, String ssn )
11 {
12 firstName = first;
13 lastName = last;
14 socialSecurityNumber = ssn;
15 }
16
17 // set first name
18 public void setFirstName( String first )
19 {
20 firstName = first;
21 }
22
92
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (5)
23 // return first name
24 public String getFirstName()
25 {
26 return firstName;
27 }
28
29 // set last name
30 public void setLastName( String last )
31 {
32 lastName = last;
33 }
34
35 // return last name
36 public String getLastName()
37 {
38 return lastName;
39 }
40
41 // set social security number
42 public void setSocialSecurityNumber( String number )
43 {
44 socialSecurityNumber = number; // should validate
45 }
46
93
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (6)
94
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (7)
1 // SalariedEmployee.java
2 // SalariedEmployee class extends Employee.
3
4 public class SalariedEmployee extends Employee {
5 private double weeklySalary;
6
7 // constructor
8 public SalariedEmployee( String first, String last,
9 String socialSecurityNumber, double salary )
10 {
11 super( first, last, socialSecurityNumber );
12 setWeeklySalary( salary );
13 }
Use superclass constructor for
14
basic fields.
15 // set salaried employee's salary
16 public void setWeeklySalary( double salary )
17 {
18 weeklySalary = salary < 0.0 ? 0.0 : salary;
19 }
20
21 // return salaried employee's salary
22 public double getWeeklySalary()
23 {
24 return weeklySalary;
25 } 95
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (8)
26
27 // calculate salaried employee's pay;
28 // override abstract method earnings in Employee
29 public double earnings()
30 {
Must implement abstract
31 return getWeeklySalary();
method earnings.
32 }
33
34 // return String representation of SalariedEmployee object
35 public String toString()
36 {
37 return "\nsalaried employee: " + super.toString();
38 }
39
40 } // end class SalariedEmployee
96
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (9)
1 // HourlyEmployee.java
2 // HourlyEmployee class extends Employee.
3
4 public class HourlyEmployee extends Employee {
5 private double wage; // wage per hour
6 private double hours; // hours worked for week
7
8 // constructor
9 public HourlyEmployee( String first, String last,
10 String socialSecurityNumber, double hourlyWage, double hoursWorked )
11 {
12 super( first, last, socialSecurityNumber );
13 setWage( hourlyWage );
14 setHours( hoursWorked );
15 }
17 // set hourly employee's wage
18 public void setWage( double wageAmount )
19 {
20 wage = wageAmount < 0.0 ? 0.0 : wageAmount;
21 }
23 // return wage
24 public double getWage()
25 {
26 return wage;
27 } 97
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (10)
29 // set hourly employee's hours worked
30 public void setHours( double hoursWorked )
31 {
32 hours = ( hoursWorked >= 0.0 && hoursWorked <= 168.0 ) ? hoursWorked : 0.0;
34 }
36 // return hours worked
37 public double getHours()
38 {
39 return hours;
40 }
42 // calculate hourly employee's pay;
43 // override abstract method earnings in Employee
44 public double earnings()
45 {
Must implement abstract
46 if ( hours <= 40 ) // no overtime
47 return wage * hours;
method earnings.
48 else
49 return 40 * wage + ( hours - 40 ) * wage * 1.5;
50 }
52 // return String representation of HourlyEmployee object
53 public String toString()
54 {
55 return "\nhourly employee: " + super.toString();
56 }
58 } // end class HourlyEmployee 98
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (11)
1 // CommissionEmployee.java
2 // CommissionEmployee class extends Employee.
3
4 public class CommissionEmployee extends Employee {
5 private double grossSales; // gross weekly sales
6 private double commissionRate; // commission percentage
8 // constructor
9 public CommissionEmployee( String first, String last,
10 String socialSecurityNumber,
11 double grossWeeklySales, double percent )
12 {
13 super( first, last, socialSecurityNumber );
14 setGrossSales( grossWeeklySales );
15 setCommissionRate( percent );
16 }
18 // set commission employee's rate
19 public void setCommissionRate( double rate )
20 {
21 commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;
22 }
24 // return commission employee's rate
25 public double getCommissionRate()
26 {
27 return commissionRate;
28 } 99
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (12)
30 // set commission employee's weekly base salary
31 public void setGrossSales( double sales )
32 {
33 grossSales = sales < 0.0 ? 0.0 : sales;
34 }
35
36 // return commission employee's gross sales amount
37 public double getGrossSales()
38 {
39 return grossSales;
40 }
41
42 // calculate commission employee's pay;
43 // override abstract method earnings in Employee
44 public double earnings() Must implement abstract
45 { method earnings.
46 return getCommissionRate() * getGrossSales();
47 }
48
49 // return String representation of CommissionEmployee object
50 public String toString()
51 {
52 return "\ncommission employee: " + super.toString();
53 }
55 } // end class CommissionEmployee 100
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (13)
1 // BasePlusCommissionEmployee.java
2 // BasePlusCommissionEmployee class extends CommissionEmployee.
3
4 public class BasePlusCommissionEmployee extends CommissionEmployee {
5 private double baseSalary; // base salary per week
6
7 // constructor
8 public BasePlusCommissionEmployee( String first, String last,
9 String socialSecurityNumber, double grossSalesAmount,
10 double rate, double baseSalaryAmount )
11 {
12 super( first, last, socialSecurityNumber, grossSalesAmount, rate );
13 setBaseSalary( baseSalaryAmount );
14 }
15
16 // set base-salaried commission employee's base salary
17 public void setBaseSalary( double salary )
18 {
19 baseSalary = salary < 0.0 ? 0.0 : salary;
20 }
22 // return base-salaried commission employee's base salary
23 public double getBaseSalary()
24 {
25 return baseSalary;
26 } 101
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (14)
102
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (15)
1 // PayrollSystemTest.java
2 // Employee hierarchy test program.
3 import java.text.DecimalFormat;
4 import javax.swing.JOptionPane;
5
6 public class PayrollSystemTest {
7
8 public static void main( String[] args )
9 {
10 DecimalFormat twoDigits = new DecimalFormat( "0.00" );
11
12 // create Employee array
13 Employee employees[] = new Employee[ 4 ];
14
15 // initialize array with Employees
16 employees[ 0 ] = new SalariedEmployee( "John", "Smith",
17 "111-11-1111", 800.00 );
18 employees[ 1 ] = new CommissionEmployee( "Sue", "Jones",
19 "222-22-2222", 10000, .06 );
20 employees[ 2 ] = new BasePlusCommissionEmployee( "Bob", "Lewis",
21 "333-33-3333", 5000, .04, 300 );
22 employees[ 3 ] = new HourlyEmployee( "Karen", "Price",
23 "444-44-4444", 16.75, 40 );
24
25 String output = ""; 103
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (16)
27 // generically process each element in array employees
28 for ( int i = 0; i < employees.length; i++ ) {
29 output += employees[ i ].toString();
30
31 // determine whether element is a BasePlusCommissionEmployee
32 if ( employees[ i ] instanceof BasePlusCommissionEmployee ) {
33
34 // downcast Employee reference to Determine whether element is a
35 // BasePlusCommissionEmployee reference BasePlusCommissionEmployee
36 BasePlusCommissionEmployee currentEmployee =
37 ( BasePlusCommissionEmployee ) employees[ i ];
38
39 double oldBaseSalary = currentEmployee.getBaseSalary();
40 output += "\nold base salary: $" + oldBaseSalary;
41
42 currentEmployee.setBaseSalary( 1.10 * oldBaseSalary );
43 output += "\nnew base salary with 10% increase is: $" +
44 currentEmployee.getBaseSalary();
Downcast Employee reference to
45
BasePlusCommissionEmployee
46 } // end if
reference
47
48 output += "\nearned $" + employees[ i ].earnings() + "\n";
49
50 } // end for
51 104
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (17)
105
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a payroll program (18)
106
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: Multiple Inheritance
111
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (2)
1 // Shape.java
2 // Shape interface declaration.
3
4 public interface Shape {
5 public double getArea(); // calculate area
6 public double getVolume(); // calculate volume
7 public String getName(); // return shape name
8
9 } // end interface Shape
112
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (3)
1 // Point.java
2 // Point class declaration implements interface Shape.
3
4 public class Point implements Shape {
5 private int x; // x part of coordinate pair
6 private int y; // y part of coordinate pair
7
8 // no-argument constructor; x and y default to 0
9 public Point()
10 {
11 // implicit call to Object constructor occurs here
12 }
13
14 // constructor
15 public Point( int xValue, int yValue )
16 {
17 // implicit call to Object constructor occurs here
18 x = xValue; // no need for validation
19 y = yValue; // no need for validation
20 }
22 // set x in coordinate pair
23 public void setX( int xValue )
24 {
25 x = xValue; // no need for validation
26 } 113
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (4)
114
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (5)
46 // declare abstract method getArea
47 public double getArea()
48 {
49 return 0.0;
50 }
51
52 // declare abstract method getVolume
Implement methods specified
53 public double getVolume()
54 {
by interface Shape
55 return 0.0;
56 }
57
58 // declare abstract method getName to return "Point"
59 public String getName()
60 {
61 return "Point";
62 }
63
64 // override toString to return String representation of Point
65 public String toString()
66 {
67 return "[" + getX() + ", " + getY() + "]";
68 }
69
70 } // end class Point 115
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (6)
1 // InterfaceTest.java
2 // Test Point, Circle, Cylinder hierarchy with interface Shape.
3 import java.text.DecimalFormat;
4 import javax.swing.JOptionPane;
5
6 public class InterfaceTest {
7
8 public static void main( String args[] )
9 {
10 // set floating-point number format
11 DecimalFormat twoDigits = new DecimalFormat( "0.00" );
12
13 // create Point, Circle and Cylinder objects
14 Point point = new Point( 7, 11 );
15 Circle circle = new Circle( 22, 8, 3.5 );
16 Cylinder cylinder = new Cylinder( 20, 30, 3.3, 10.75 );
17
18 // obtain name and string representation of each object
19 String output = point.getName() + ": " + point + "\n" +
20 circle.getName() + ": " + circle + "\n" +
21 cylinder.getName() + ": " + cylinder + "\n";
22
23 Shape arrayOfShapes[] = new Shape[ 3 ]; // create Shape array
24
116
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (7)
25 // aim arrayOfShapes[ 0 ] at subclass Point object
26 arrayOfShapes[ 0 ] = point;
27
28 // aim arrayOfShapes[ 1 ] at subclass Circle object
29 arrayOfShapes[ 1 ] = circle;
30
31 // aim arrayOfShapes[ 2 ] at subclass Cylinder object
32 arrayOfShapes[ 2 ] = cylinder;
33
34 // loop through arrayOfShapes to get name, string
35 // representation, area and volume of every Shape in array
36 for ( int i = 0; i < arrayOfShapes.length; i++ ) {
37 output += "\n\n" + arrayOfShapes[ i ].getName() + ": " +
38 arrayOfShapes[ i ].toString() + "\nArea = " +
39 twoDigits.format( arrayOfShapes[ i ].getArea() ) +
40 "\nVolume = " +
41 twoDigits.format( arrayOfShapes[ i ].getVolume() );
42 }
43
44 JOptionPane.showMessageDialog( null, output ); // display output
45
46 System.exit( 0 );
48 } // end main
50 } // end class InterfaceTest
117
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
P: a shape hierarchy (8)
118
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
Exception Handling: exception types
Exception:
an object representing details of a program failure
the package java.lang defines an hierarchy of exception types
that can be thrown during the execution of a program
Error:
usually reserved for
runtime-system errors
Checked Exceptions:
extend java.lang.Exception
must be explicitly caught or
propagated (declared thrown)
Unchecked Exceptions:
extend
java.lang.RuntimeException
don't have to be declared thrown
can be caught but have not to be
119
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
EH: Checked Exceptions
class java.lang.Exception
class java.lang.ClassNotFoundException
class java.lang.CloneNotSupportedException
class java.io.FileNotFoundException
class java.security.GeneralSecurityException
class java.lang.IllegalAccessException
class java.lang.InstantiationException
class java.lang.InterruptedException
class java.io.IOException
class java.lang.NoSuchFieldException
class java.lang.NoSuchMethodException
...
120
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
EH: Unchecked Exceptions
class java.lang.RunTimeException
class java.lang.ArithmeticException
class java.lang.ArrayStoreException
class java.lang.ClassCastException
class java.util.EmptyStackException
class java.lang.IllegalArgumentException
class java.lang.IllegalMonitorStateException
class java.lang.IllegalStateException
class java.lang.IndexOutOfBoundsException
class java.lang.NegativeArraySizeException
class java.util.NoSuchElementException
class java.lang.NullPointerException
class java.lang.SecurityException
class java.lang.UnsupportedOperationException
...
121
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
EH: Throwing exceptions
the instruction:
throw
new ExceptionType("optional-diagnostic-string");
124
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
EH: ArithmeticException (1)
1 // DivideByZeroTest.java
2 // An exception-handling example that checks for divide-by-zero.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public class DivideByZeroTest extends Jframe implements ActionListener {
9
10 private JTextField inputField1, inputField2, outputField;
11 private int number1, number2, result;
12
13 // set up GUI
14 public DivideByZeroTest()
15 {
16 super( "Demonstrating Exceptions" );
17
18 // get content pane and set its layout
19 Container container = getContentPane();
20 container.setLayout( new GridLayout( 3, 2 ) );
21
22 // set up label and inputField1
23 container.add(
24 new JLabel( "Enter numerator ", SwingConstants.RIGHT ) );
25 inputField1 = new JTextField();
26 container.add( inputField1 ); 125
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
EH: ArithmeticException (2)
27
28 // set up label and inputField2; register listener
29 container.add( new JLabel( "Enter denominator and press Enter ",
30 SwingConstants.RIGHT ) );
31 inputField2 = new JTextField();
32 container.add( inputField2 );
33 inputField2.addActionListener( this );
34
35 // set up label and outputField
36 container.add( new JLabel( "RESULT ", SwingConstants.RIGHT ) );
37 outputField = new JTextField();
38 container.add( outputField );
39
40 setSize( 425, 100 );
41 setVisible( true );
42
43 } // end DivideByZeroTest constructor
44
45 // process GUI events
46 public void actionPerformed( ActionEvent event )
47 {
48 outputField.setText( "" ); // clear outputField
49
126
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
EH: ArithmeticException (3)
50 // read two numbers and calculate quotient
51 try {
52 number1 = Integer.parseInt( inputField1.getText() );
53 number2 = Integer.parseInt( inputField2.getText() );
54
55 result = quotient( number1, number2 );
56 outputField.setText( String.valueOf( result ) );
57 }
58
59 // process improperly formatted input
60 catch ( NumberFormatException numberFormatException ) {
61 JOptionPane.showMessageDialog( this,
62 "You must enter two integers", "Invalid Number Format",
63 JOptionPane.ERROR_MESSAGE );
64 }
65
66 // process attempts to divide by zero
67 catch ( ArithmeticException arithmeticException ) {
68 JOptionPane.showMessageDialog( this,
69 arithmeticException.toString(), "Arithmetic Exception",
70 JOptionPane.ERROR_MESSAGE );
71 }
72
73 } // end method actionPerformed
74 127
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
EH: ArithmeticException (4)
75 // demonstrates throwing an exception when a divide-by-zero occurs
76 public int quotient( int numerator, int denominator )
77 throws ArithmeticException
78 {
79 return numerator / denominator;
80 }
81
82 public static void main( String args[] )
83 {
84 DivideByZeroTest application = new DivideByZeroTest();
85 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
86 }
87
88 } // end class DivideByZeroTest
128
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
EH: Text Output
try {
FileWriter writer = new FileWriter("name-of-file"));
while( there is more text to write ) {
. . .
writer.write ("next-piece-of-text");
. . .
}
writer.close();
}
catch(IOException e) {
something went wrong with accessing the file
}
129
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
EH: Text Input
try {
BufferedReader reader = new BufferedReader(
new FileReader("name-of-file"));
String line = reader.readLine();
while(line != null) {
do something with line
line = reader.readLine();
}
reader.close();
}
catch(FileNotFoundException e) {
the specified file could not be found
}
catch(IOException e) {
something went wrong with reading or closing
}
130
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
Java Language: Primitive Data Types
(integers)
132
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Reference Data Types
133
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Scope
134
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Arithmetic Operators
135
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Relational and Conditional Operators
137
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Assignment Operators
op1= op2;
?: op1 ? op2 : op3 If op1 is true, returns op2. Otherwise, returns op3.
139
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Control Flow Statements - looping
do {
statement(s)
} while (boolean expression);
141
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Control Flow Statements – exception handling
try {
statement(s)
} catch (exceptiontype name) {
statement(s)
} catch (exceptiontype name) {
statement(s)
} finally {
statement(s)
}
The try statement identifies a block of statements within which an exception might be thrown.
The catch statement must be associated with a try statement and identifies a block of
statements that are executed if an exception of a particular type occurs within the try block.
The finally statement (optional) must be associated with a try statement and identifies a block
of statements that are executed regardless of whether or not an error occurs within the try
block.
142
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Control Flow Statements – branching
statementName: someJavaStatement ;
return value; terminates the current method and return a value to the
method's caller
143
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Classes – example
144
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Class Declaration
145
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Class Body
146
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Constructors
public Stack( ) {
items = new Vector(10); new Stack( );
}
148
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Methods
(passed by value)
149
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Instance and Class Variables - definitions
151
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Instance and Class Variables - examples
class AnIntegerNamedX { . . .
int x; AnIntegerNamedX x1 = new AnIntegerNamedX();
public int getX() { AnIntegerNamedX x2 = new AnIntegerNamedX();
return x;
x1.setX(5);
} x2.setX(7);
public void setX(int newX) System.out.println("x1.x = " + x1.getX()); //x1.x = 5
{ x = newX; System.out.println("x2.x = " + x2.getX()); //x2.x = 7
} . . .
}
. . .
class AnIntegerNamedX {
AnIntegerNamedX x1 = new AnIntegerNamedX();
static int x;
AnIntegerNamedX x2 = new AnIntegerNamedX();
public int getX() {
x1.setX(5);
return x;
x2.setX(7);
}
AnIntegerNamedX.x = 9;
public void setX(int newX) {
System.out.println("x1.x = " + x1.getX()); //x1.x = 9
x = newX;
System.out.println("x2.x = " + x2.getX()); //x2.x = 9
}
System.out.println("x = " + AnIntegerNamedX.x);//x = 9
}
. . .
152
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Class Methods - examples
. . .
class AnIntegerNamedX {
AnIntegerNamedX x1 = new AnIntegerNamedX();
static int x; AnIntegerNamedX x2 = new AnIntegerNamedX();
x1.setX(5);
static public int getX() {
x2.setX(7);
return x;
AnIntegerNamedX.x = 9;
} AnIntegerNamedX.setX(11);
System.out.println("x1.x = " + x1.getX()); // x1.x = 11
static public void setX(int newX) {
System.out.println("x2.x = " + x2.getX()); // x2.x = 11
x = newX;
System.out.println("x = " + AnIntegerNamedX.x); // x = 11
} System.out.println("x = " + AnIntegerNamedX.getX());//x = 11
} . . .
153
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Interfaces
Package:
a collection of related classes and interfaces providing
access protection and namespace management.
package graphics;
public class Circle extends Graphic implements Draggable {
...
}
package graphics;
public class Rectangle extends Graphic implements Draggable {
...
}
import graphics.Circle; import graphics.*; 155
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Creating and Using Objects
156
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Creating Arrays
Creating an Array
anArray = new int[10]; // create an array of integers
Copying Arrays
System.arraycopy (Object source, int srcIndex,
Object dest, int destIndex,
int length)
source
158
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Lists (1)
firstNode lastNode
H D ... Q
159
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Lists (2)
(a) firstNode
7 11
new Listnode
12
(b) firstNode
7 11
new Listnode
12
160
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Lists (3)
(a) firstNode lastNode new Listnode
12 7 11 5
12 7 11 5
12 7 11 5
12 7 11 5
removeItem
162
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Lists (5)
(a) firstNode lastNode
12 7 11 5
12 7 11 5
removeItem
163
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Lists (6)
1 // List.java
2 // ListNode and List class declarations.
4 package lists;
5 // class to represent one node in a list
6 class ListNode {
7
8 // package access members; List can access these directly
9 Object data;
Self-referential
class
10 ListNode nextNode;
11
ListNode contains data
12 // create a ListNode that refers to object and link to nextNode
13 ListNode( Object object )
14 {
15 this( object, null );
16 }
17
18 // create ListNode that refers to Object and to next ListNode
19 ListNode( Object object, ListNode node )
20 {
21 data = object;
22 nextNode = node;
23 }
24
164
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Lists (7)
25 // return reference to data in node
26 Object getObject()
27 {
28 return data; // return Object in this node
29 }
30
31 // return reference to next node in list
32 ListNode getNext()
33 {
34 return nextNode; // get next node
35 }
36
37 } // end class ListNode
38
39 // class List declaration
40 public class List {
41 private ListNode firstNode;
42 private ListNode lastNode;
43 private String name; // string like "list" used in printing
44
45 // construct empty List with "list" as the name
46 public List()
47 {
48 this( "list" );
49 } 165
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Lists (8)
51 // construct an empty List with a name
52 public List( String listName )
53 {
54 name = listName;
55 firstNode = lastNode = null;
56 }
57
58 // insert Object at front of List
59 public synchronized void insertAtFront( Object insertItem )
60 {
61 if ( isEmpty() ) // firstNode and lastNode refer to same object
62 firstNode = lastNode = new ListNode( insertItem );
64 else // firstNode refers to new node
65 firstNode = new ListNode( insertItem, firstNode );
66 }
67
68 // insert Object at end of List
69 public synchronized void insertAtBack( Object insertItem )
70 {
71 if ( isEmpty() ) // firstNode and lastNode refer to same Object
72 firstNode = lastNode = new ListNode( insertItem );
73
74 else // lastNode's nextNode refers to new node
75 lastNode = lastNode.nextNode = new ListNode( insertItem );
76 } 166
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Lists (9)
77
78 // remove first node from List
79 public synchronized Object removeFromFront() throws EmptyListException
80 {
81 if ( isEmpty() ) // throw exception if List is empty
82 throw new EmptyListException( name );
83
84 Object removedItem = firstNode.data; // retrieve data being removed
85
86 // update references firstNode and lastNode
87 if ( firstNode == lastNode )
88 firstNode = lastNode = null;
89 else
90 firstNode = firstNode.nextNode;
91
92 return removedItem; // return removed node data
93
94 } // end method removeFromFront
95
167
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Lists (10)
96 // remove last node from List
97 public synchronized Object removeFromBack() throws EmptyListException
98 {
99 if ( isEmpty() ) // throw exception if List is empty
100 throw new EmptyListException( name );
101
102 Object removedItem = lastNode.data; // retrieve data being removed
103
104 // update references firstNode and lastNode
105 if ( firstNode == lastNode )
106 firstNode = lastNode = null;
107
108 else { // locate new last node
109 ListNode current = firstNode;
110
111 // loop while current node does not refer to lastNode
112 while ( current.nextNode != lastNode )
113 current = current.nextNode;
114
115 lastNode = current; // current is new lastNode
116 current.nextNode = null;
117 }
118
119 return removedItem; // return removed node data
121 } // end method removeFromBack 168
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Lists (11)
123 // determine whether list is empty
124 public synchronized boolean isEmpty()
125 {
126 return firstNode == null; // return true if List is empty
127 }
128
129 // output List contents
130 public synchronized void print()
131 {
132 if ( isEmpty() ) {
133 System.out.println( "Empty " + name );
134 return;
135 }
136
137 System.out.print( "The " + name + " is: " );
138 ListNode current = firstNode;
139
140 // while not at end of list, output current node's data
141 while ( current != null ) {
142 System.out.print( current.data.toString() + " " );
143 current = current.nextNode;
144 }
146 System.out.println( "\n" );
147 }
149 } // end class List 169
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Lists (12)
1 // EmptyListException.java
2 // Class EmptyListException declaration.
4 package lists;
5 public class EmptyListException extends RuntimeException {
6
7 // no-argument constructor
8 public EmptyListException()
9 {
10 this( "List" ); // call other EmptyListException constructor
11 }
12
13 // constructor
14 public EmptyListException( String name )
15 {
16 super( name + " is empty" ); // call superclass constructor
17 }
18
19 } // end class EmptyListException
170
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Lists (13)
1 // ListTest.java
2 // ListTest class to demonstrate List capabilities.
5 import lists.*;
6 public class ListTest {
7
8 public static void main( String args[] )
9 {
10 List list = new List(); // create the List container
11
12 // objects to store in list
13 Boolean bool = Boolean.TRUE;
14 Character character = new Character( '$' );
15 Integer integer = new Integer( 34567 );
16 String string = "hello";
17
18 // insert references to objects in list
19 list.insertAtFront( bool );
20 list.print();
21 list.insertAtFront( character );
22 list.print();
23 list.insertAtBack( integer );
24 list.print();
25 list.insertAtBack( string );
26 list.print();
171
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Lists (14)
28 // remove objects from list; print after each removal
29 try {
30 Object removedObject = list.removeFromFront();
31 System.out.println( removedObject.toString() + " removed" );
32 list.print();
33
34 removedObject = list.removeFromFront();
35 System.out.println( removedObject.toString() + " removed" );
36 list.print();
37
38 removedObject = list.removeFromBack();
39 System.out.println( removedObject.toString() + " removed" );
40 list.print();
41
42 removedObject = list.removeFromBack();
43 System.out.println( removedObject.toString() + " removed" );
44 list.print();
46 } // end try block
47
48 // catch exception if remove is attempted on an empty List
49 catch ( EmptyListException emptyListException ) {
50 emptyListException.printStackTrace();
51 }
52 }
54 } // end class ListTest 172
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JL: Lists (15)
$ removed
The list is: true 34567 hello
true removed
The list is: 34567 hello
hello removed
The list is: 34567
34567 removed
Empty list
173
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
Case Study: a model for a taxi company
• The company operates both individual taxis and shuttles
• The taxis transport an individual (or small group) from one location to
another
• The shuttles pick up individuals from different locations and transport them
to their several destinations
• When the company receives a call, it tries to schedule a vehicle to pick up the
fare
• If it has no free vehicles, the fare is lost
• When a vehicle arrives at a pickup location, the driver notifies the company
• When a passenger is dropped off at their destination, the driver notifies the
company
• The system store details about passenger requests that cannot be satisfied
• The system provides details of how much time vehicles spend in each of the
following activities: carrying passengers, going to pickup locations, and
being idle
174
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
CS: identifying initial classes
Verb/Noun method Nouns Verbs
nouns in requirement Company operates taxis and shuttles
specifications
receives a call
correspond to classes
verbs correspond to schedules a vehicle
methods Taxi transports one or more passenger
Shuttle transports one or more passenger
Passenger
Location
Passenger-source calls the company
Vehicle pick up individual
arrives at pickup location
notifies company of arrival
notifies company of drop-off
175
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
CS: interactions among classes (1)
CRC cards Class
(Class/Responsibilities/Collaborators) Responsibilities Collaborators
Scenarios (Use cases)
PassengerSource TaxiCompany
Create a Passenger Passenger Receive a pickup request Passenger
Request a pickup TaxiCompany Location
Generate pickup and destination Location Store a collection of vehicles Collection
Schedule a vehicle Vehicle
Passenger
Direct vehicle to pickup
Receive pickup and destination Location
Receives notification of arrival
Provide pickup location
Pass passenger to vehicle
Provide destination location
Receives notification of drop-off 176
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
CS: interactions among classes (2)
Vehicle
Indicate wether free
Receive pickup location Location
Maintain a current location
Notify of pickup arrival TaxiCompany
Notify of passenger drop-off
Receive passenger Passenger
Request destination location
Offload passenger
Taxi Shuttle
Go to pickup location Location Choose next target location Collection
Go to passenger destination Add location to collection
177
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
CS: class design (1)
UML (Unified Modeling Language)
Class
Fields
Methods
178
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
CS: class design (2)
public class PassengerSource public class Location
{ {
private TaxiCompany company; public Location()
public PassengerSource(TaxiCompany company) {
{ }
if(company == null) { }
throw new NullPointerException("company");
}
this.company = company;
}
public boolean requestPickup()
{
Passenger passenger = createPassenger();
return company.requestPickup(passenger);
}
private Passenger createPassenger()
{
return new Passenger(new Location(), new Location());
}
}
179
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
CS: class design (3)
public class Passenger
{
private Location pickup;
private Location destination;
public Passenger(Location pickup, Location destination)
{
if(pickup == null) {
throw new NullPointerException("Pickup location");
}
if(destination == null) {
throw new NullPointerException("Destination location");
}
this.pickup = pickup;
this.destination = destination;
}
public Location getPickupLocation()
{
return pickup;
}
public Location getDestination()
{
return destination;
}
} 180
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
CS: class design (4)
import java.util.Iterator;
import java.util.List;
import java.util.LinkedList;
public class TaxiCompany
{
private List vehicles; public void arrivedAtPickup(Vehicle vehicle)
public TaxiCompany() {
{ }
vehicles = new LinkedList(); public void arrivedAtDestination(
} Vehicle vehicle, Passenger passenger)
public boolean requestPickup(Passenger passenger) {
{ }
Vehicle vehicle = scheduleVehicle(); private Vehicle scheduleVehicle()
if(vehicle != null) { {
vehicle.setPickupLocation( Iterator it = vehicles.iterator();
passenger.getPickupLocation());
while(it.hasNext()) {
return true;
Vehicle vehicle = (Vehicle) it.next();
}
if(vehicle.isFree()) {
else {
return vehicle;
return false;
}
}
}
}
return null;
}
} 181
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
CS: class design (5)
public abstract class Vehicle public abstract void setPickupLocation(Location location);
{ public abstract void pickup(Passenger passenger);
private TaxiCompany company; public abstract boolean isFree();
private Location location; public abstract void offloadPassenger();
private Location targetLocation; public Location getLocation()
public Vehicle(TaxiCompany company, Location location) {
{ return location;
if(company == null) { }
throw new NullPointerException("company"); public void setLocation(Location location)
} {
if(location == null) { if(location != null) { this.location = location; }
throw new NullPointerException("location"); else { throw new NullPointerException(); }
} }
this.company = company; public Location getTargetLocation()
this.location = location; {
targetLocation = null; return targetLocation;
} }
public void notifyPickupArrival() public void setTargetLocation(Location location)
{ {
company.arrivedAtPickup(this); if(location != null) { targetLocation = location; }
} else { throw new NullPointerException(); }
public void notifyPassengerArrival(Passenger passenger) }
{ public void clearTargetLocation()
company.arrivedAtDestination(this, passenger); {
} targetLocation = null;
}
} 182
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
CS: class design (6)
public class Taxi extends Vehicle
{
public Taxi(TaxiCompany company, Location location)
{
super(company, location);
}
public boolean isFree()
{
return getTargetLocation() == null;
}
public void setPickupLocation(Location location)
{
setTargetLocation(location);
}
public void pickup(Passenger passenger)
{
setTargetLocation(passenger.getDestination());
}
public void offloadPassenger()
{
clearTargetLocation();
}
}
183
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
CS: class design (7)
public class Shuttle extends Vehicle
{
private List destinations;
private List passengers;
public Shuttle(TaxiCompany company, Location location)
{
super(company, location);
destinations = new LinkedList();
passengers = new LinkedList();
}
public boolean isFree()
{ public void pickup(Passenger passenger)
return true; {
} passengers.add(passenger);
public void setPickupLocation(Location location) destinations.add(passenger.getDestination());
{ chooseTargetLocation();
destinations.add(location); }
chooseTargetLocation(); private void chooseTargetLocation()
} {
}
public void offloadPassenger()
{
}
} 184
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
Object Oriented Analysis/Design
Object Oriented Analysis (OOA)
The process of analysis and specification of the problem requirements
The problem domain is formally represented by classes, objects and their
interactions
It defines the way users can interact with the system
Object Oriented Design (OOD)
The process of construction of a problem solution through the design of
the object structures, responsibilities and relations
Unified Modeling Language (UML)
a graphic language used to represent the results of the OOA/D processes
by means of different diagrams types
(http://www.omg.org/uml/)
Modelling tools
• Papyrus UML (http://www.papyrusuml.org/)
• Omondo EclipseUML (http://www.omondo.com/)
• ArgoUML (http://argouml.tigris.org/)
185
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML diagram types (1)
System structure
Class diagrams
• Models classes, or “building blocks” of a system
Object diagrams
• Snapshot (model) of system’s objects and relationships at specific
point in time
Component diagrams
• Model components such as graphics resources and class packages
that make up the system
Deployment diagrams
• Model hardware, memory and runtime resources
186
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML diagram types (2)
System behavior
Statechart diagrams
• Model how object changes state
• Condition/behavior of an object at a specific time
Activity diagrams
• Flowchart modeling order and actions performed by object
Collaboration diagrams
• Emphasize what interactions occur
Sequence diagrams
• Emphasize when interactions occur
Use-case diagrams
• Represent interaction between user and system
187
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: an elevator simulation
188
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: discovering classes
Class Verb phrases
Elevator moves to other floor, arrives at a floor, resets elevator
button, rings elevator bell, signals its arrival, opens its
door, closes its door
ElevatorShaft turns off light, turns on light, resets floor button
Person walks on floor, presses floor button, presses elevator button,
rides elevator, enters elevator, exits elevator
Floor [none in the problem statement]
FloorButton requests elevator
ElevatorButton closes elevator door, signals elevator to move to opposite
floor
Floo rDoor signals person to enter elevator (by opening)
ElevatorDoor signals person to exit elevator (by opening), opens floor
door, closes floor door
Bell [none in the problem statement]
Light [none in the problem statement]
Verb phrases for each class in simulator
189
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML class diagrams
+ :public ElevatorSimulation ElevatorShaft ElevatorDoor
Elevator
ElevatorButton Bell
- moving : Boolean = false
- summoned : Boolean = false
- currentFloor : Integer = 1 - pressed : Boolean = false
- destinationFloor : Integer = 2 + resetButton( ) + ringBell( )
- capacity : Integer = 1 + pressButton( )
- travelTime : Integer = 5
Location
- locationName : String
- capacity : Integer = 1 {frozen}
# setLocationName( String ) : void
+ getLocationName( ) : String
+ getCapacity( ) : Integer
+ getButton( ) : Button
+ getDoor( ) : Door
Elevator Floor
- moving : Boolean = false
- summoned : Boolean = false
- currentFloor : Integer + getButton( ) : Button
- destinationFloor : Integer + getDoor( ) : Door
- travelTime : Integer = 5
+ ride( ) : void
+ requestElevator( ) : void
+ enterElevator( ) : void
+ exitElevator( ) : void
+ departElevator( ) : void
+ getButton( ) : Button
+ getDoor( ) : Door
191
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML class diagrams (1)
Location Light
- locationName : String
- lightOn : Boolean = false
# setLocationName( String ) : void
+ getLocationName( ) : String + turnOnLight( ) : void
+ getButton( ) : Button + turnOffLight( ) : void
+ getDoor( ) : Door
ElevatorSimulation
- numberOfPeople : Integer = 0
Person + addPerson( ) : void
- ID : Integer
- moving : Boolean = true Floor
- location : Location
- maxTravelTime : Integer = 10 * 60
+ getButton( ) : Button
+ getDoor( ) : Door
+ doorOpened( ) : void
Bell
192
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML class diagrams (2)
Elided diagrams
Class attributes and operations ignored
Solid line is an association, or relationship between classes
Numbers near lines express multiplicity values
• Indicate how many objects of class participate association
Symbol Meaning
0 None
1 One
m An integer value
0..1 Zero or one
m, n m or n
m..n At least m, but not more than n
* Zero or more
0..* Zero or more
1..* One or more
Multiplicity types
193
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML class diagrams (3)
ElevatorShaft
1 1
2 1
1 1
Requests
FloorButton Elevator
Signals
arrival 1
1
1
ElevatorShaft
Signals
1 arrival
1
Informs of
pressing
Closes Resets
2 1
1 2 Presses
Door Button Person
1 Signals 1 1
1 arrival 1
1 1 1 1
Waits for
opening
Opens/Closes
1 1
1 Signals
1
to move Occupies
ElevatorDoor Elevator
1 Signals
1 1 Signals 1 1 arrival
arrival
Opens/Closes Travels to
Signals
arrival 2 1
Rings
1
Location
1
1 Bell
195
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML object diagrams
: ElevatorSimulation
: ElevatorShaft
: Bell
196
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML component diagrams (1)
197
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML component diagrams (2)
model
executable
ElevatorCaseStudy.class <<file>>
ElevatorSimulation.java
compilation
imports ElevatorSimulation-
Listener
view
<file>>
<<file>>
imports ElevatorView.java
ElevatorCaseStudy.java
controller
imports
<file>>
ElevatorController.java
198
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML statechart diagrams
State
Describes an object’s condition at a given time
Statechart diagram
Express how an object can change state
Express under what conditions an object can change state
Diagram notation
• States are represented by rounded rectangles
• e.g., “Not Pressed” and “Pressed”
• Solid circle (with attached arrowhead) designates initial state
• Arrows represent transitions (state changes)
• Objects change state in response to messages
» e.g., “buttonPressed” and “buttonReset”
• Diagram for FloorButton and ElevatorButton objects:
buttonReset
Not pressed Pressed
buttonPressed
199
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML activity diagrams
200
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML activity diagram for a Person object
move toward floor button
enter elevator
exit elevator
201
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML activity diagram for an Elevator object
[floor button
pressed]
[elevator button
pressed]
[summoned]
[not summoned]
202
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML collaboration diagrams (1)
Collaboration-diagram notation
Objects are written in form objectName : ClassName
• Disregard objectName only when concerned about class
Solid lines connect collaborating objects
Arrows represent messages
• Indicates direction of collaboration
• Points toward object receiving message
• Can be implemented as a methods (synchronous calls) in Java
Message names appear next to arrows
Diagram of a person pressing a floor button:
p ressButto n( )
: Person : FloorButton
203
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML collaboration diagrams (2)
204
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML collaboration diagrams (3)
4 : eleva to rArrived ()
:Eleva tor
3.1.1.1 : enterEleva to r() 3.2.1 : exitEleva to r()
3.2 : d o o rOp ened ()
1: resetButto n() 2: ring Bell( )
3: o p enDo o r()
205
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML sequence diagrams (1)
Sequence Diagrams
Shows interactions among objects
• Shows messages passed among objects over time
Rectangle enclosing an object name represents that object
• Use same naming conventions as collaboration diagrams
Lifeline
• Dotted line running down from an object name
• Actions occur on lifeline in chronological order, top to bottom
Arrows
• Dashed arrows
• Represent “return messages,” return of control to object
• Solid arrows
• A message sent from one object to another
206
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML sequence diagrams (2)
Person ElevatorShaft elevatorDoor : ElevatorDoor
[ !floorDoor.isDoorOpen() ]
pressButton( )
buttonPressed( )
requestElevator( )
*[ !floorDoor.isDoorOpen() ] wait( )
elevatorArrived( )
openDoor( )
openDoor( )
setLocation( elevator )
207
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: UML use-case diagrams
Use case
Represents capabilities that systems provide to clients
Use-case diagram
Models use cases in system
• Stick figure represents actor
• Actor represents set of roles that external entity can play
• System box (rectangle) contains system use cases
• Ovals represent use cases
Create Person
User
208
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
Java Class Library: Language Package (java.lang)
Class Description
Boolean The Boolean class wraps a value of the primitive type boolean in an object.
Character The Character class wraps a value of the primitive type char in an object.
Double The Double class wraps a value of the primitive type double in an object.
Float The Float class wraps a value of primitive type float in an object.
Integer The Integer class wraps a value of the primitive type int in an object.
Long The Long class wraps a value of the primitive type long in an object.
Math The class Math contains methods for performing basic numeric operations such as the elementary
exponential, logarithm, square root, and trigonometric functions.
Number The abstract class Number is the superclass of classes Byte, Double, Float, Integer, Long, and Short.
Short The Short class is the standard wrapper for short values.
209
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Character Class – Constructor and Methods
212
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: Design Patterns
214
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: Short Passages Pattern (1)
Context
"...Long, sterile corridors set the scene for
everything bad about modern architecture..."
Problem
a lengthy description of the problem, including
• a depressing picture
• issues of light and furniture
• research about patient anxiety in hospitals
• research that suggests that corridors over 50 ft are
considered uncomfortable
215
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: Short Passages Pattern (2)
216
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: Short Passages Pattern (3)
Solution
Keep passages short
Make them as much like rooms as possible, with carpets or wood
on the floor, furniture, bookshelves, beautiful windows
Make them generous in shape and always give them plenty of
light; the best corridors and passages of all are those which have
windows along an entire wall
217
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: Categories of Design Patterns
Creational
Address issues related to object creation
• prevent from creating more than one object of class
• defer at run time what type of objects to be created
Structural
Organize classes and objects
Behavioral
Assign responsibilities to objects
Concurrent
Used in multithreaded systems
Architectural
Specify how subsystems interact with each other
218
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Utilities Package (java.util)
Collections framework
a unified architecture for representing and manipulating
collections
Interfaces
• abstract data types representing collections
• Interfaces allow collections to be manipulated independently of the
details of their representation
Implementations
• concrete implementations of the collection interfaces
(reusable data structures)
Algorithms
• methods that perform useful computations, like searching and
sorting, on objects that implement collection interfaces
• algorithms are polymorphic because the same method can be used
on many different implementations of the appropriate collections
interface (reusable functionality) 219
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Collection Interfaces (1)
220
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Collection Interfaces (2)
Collection
a group of objects, known as its elements
the least common denominator that all collections implement
used to pass collections around and manipulate them when maximum generality is desired
JDK doesn't provide any direct implementations of this interface
Set
a collection that cannot contain duplicate elements
models the mathematical set abstraction
SortedSet
a Set that maintains its elements in ascending order
List
an ordered collection (sometimes called a sequence)
can contain duplicate elements
elements can be accessed by their integer index (position).
Map
an object that maps keys to values
cannot contain duplicate keys
each key can map to at most one value
SortedMap
a Map that maintains its mappings in ascending key order
221
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: Strategy Pattern (1)
Context
A class can benefit from different variants for an algorithm
Clients sometimes want to replace standard algorithms with
custom versions
Solution
Define an interface type that is an abstraction for the
algorithm
Actual strategy classes realize this interface type.
Clients can supply strategy objects
Whenever the algorithm needs to be executed, the context
class calls the appropriate methods of the strategy object
222
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: Strategy Pattern (2)
223
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: A Strategy Pattern Example
224
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: Iterator Pattern (1)
Context
An aggregate object contains element objects
Clients need access to the element objects
The aggregate object should not expose its internal
structure
Multiple clients may want independent access
Solution
Define an iterator that fetches one element at a time
Each iterator object keeps track of the position of the next
element
If there are several aggregate/iterator variations, it is best if
the aggregate and iterator classes realize common interface
types
225
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: Iterator Pattern (2)
226
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: An Iterator Pattern Example
Name in Design Pattern Actual Name (linked lists)
Aggregate List
ConcreteAggregate LinkedList
Iterator ListIterator
createIterator() listIterator()
next() next()
boolean add (Object o) Ensures that this collection contains the specified element.
boolean addAll (Collection c) Adds all of the elements in the specified collection to this collection.
void clear () Removes all of the elements from this collection.
boolean contains (Object o) Returns true if this collection contains the specified element.
boolean containsAll (Collection c) Returns true if this collection contains all of the elements in the specified collection.
boolean equals (Object o) Compares the specified object with this collection for equality.
int hashCode () Returns the hash code value for this collection.
boolean isEmpty () Returns true if this collection contains no elements.
Iterator iterator () Returns an iterator over the elements in this collection.
boolean remove (Object o) Removes a single instance of the specified element from this collection, if it is present.
boolean removeAll (Collection c) Removes all this collection's elements that are also contained in the specified collection.
boolean retainAll (Collection c) Retains only the elements in this collection that are contained in the specified collection.
int size () Returns the number of elements in this collection.
Object[] toArray () Returns an array containing all of the elements in this collection.
Object[] toArray (Object[] a) Returns an array containing all of the elements in this collection whose runtime type is that
of the specified array.
228
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Set Interface – Methods
boolean add (Object o) Adds the specified element to this set if it is not already present.
boolean addAll (Collection c) Adds all of the elements in the specified collection to this set if they're not already present.
void clear () Removes all of the elements from this set.
boolean contains (Object o) Returns true if this set contains the specified element.
boolean containsAll (Collection c) Returns true if this set contains all of the elements of the specified collection.
boolean equals (Object o) Compares the specified object with this set for equality.
int hashCode () Returns the hash code value for this set.
boolean isEmpty () Returns true if this set contains no elements.
Iterator iterator () Returns an iterator over the elements in this set.
boolean remove (Object o) Removes the specified element from this set if it is present.
boolean removeAll (Collection c) Removes from this set all of its elements that are contained in the specified collection.
boolean retainAll (Collection c) Retains only the elements in this set that are contained in the specified collection.
int size () Returns the number of elements in this set (its cardinality).
Object[] toArray () Returns an array containing all of the elements in this set.
Object[] toArray (Object[] a) Returns an array containing all of the elements in this set whose runtime type is that of the
specified array.
229
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: SortedSet Interface – Methods
Comparator comparator () Returns the comparator associated with this sorted set,
or null if it uses its elements' natural ordering.
Object first () Returns the first (lowest) element currently in this
sorted set.
SortedSet headSet (Object toElement) Returns a view of the portion of this sorted set whose
elements are strictly less than toElement.
Object last () Returns the last (highest) element currently in this
sorted set.
SortedSet subSet (Object fromElement, Object toElement) Returns a view of the portion of this sorted set whose
elements range from fromElement, inclusive, to
toElement, exclusive.
SortedSet tailSet (Object fromElement) Returns a view of the portion of this sorted set whose
elements are greater than or equal to fromElement.
230
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: List Interface – Methods (1)
void add (int index, Object element) Inserts the specified element at the specified position in this list.
boolean add (Object o) Appends the specified element to the end of this list.
boolean addAll (Collection c) Appends all of the elements in the specified collection to the end of this list, in
the order that they are returned by the specified collection's iterator.
boolean addAll (int index, Collection c) Inserts all of the elements in the specified collection into this list at the specified
position.
void clear () Removes all of the elements from this list.
boolean contains (Object o) Returns true if this list contains the specified element.
boolean containsAll (Collection c) Returns true if this list contains all of the elements of the specified collection..
boolean equals (Object o) Compares the specified object with this list for equality.
Object get (int index) Returns the element at the specified position in this list.
int hashCode () Returns the hash code value for this list.
int indexOf (Object o) Returns the index in this list of the first occurrence of the specified element, or -1
if this list does not contain this element.
boolean isEmpty () Returns true if this list contains no elements.
231
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: List Interface – Methods (2)
Iterator iterator () Returns an iterator over the elements in this list in proper sequence.
int lastIndexOf (Object o) Returns the index in this list of the last occurrence of the specified element, or -1 if
this list does not contain this element.
ListIterator listIterator () Returns a list iterator of the elements in this list (in proper sequence).
ListIterator listIterator (int index) Returns a list iterator of the elements in this list (in proper sequence), starting at the
specified position in this list.
Object remove (int index) Removes the element at the specified position in this list.
boolean remove (Object o) Removes the first occurrence in this list of the specified element.
boolean removeAll (Collection c) Removes from this list all the elements that are contained in the specified collection.
boolean retainAll (Collection c) Retains only the elements in this list that are contained in the specified collection.
Object set (int index, Object element) Replaces the element at the specified position in this list with the specified element.
int size () Returns the number of elements in this list.
List subList (int fromIndex, int toIndex) Returns a view of the portion of this list between the specified fromIndex, inclusive,
and toIndex, exclusive.
Object[] toArray () Returns an array containing all of the elements in this list in proper sequence.
Object[] toArray (Object[] a) Returns an array containing all of the elements in this list in proper sequence; the
runtime type of the returned array is that of the specified array.
232
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Map Interface – Methods
boolean containsKey (Object key) Returns true if this map contains a mapping for the specified key.
boolean containsValue (Object value) Returns true if this map maps one or more keys to the specified value.
Set entrySet () Returns a set view of the mappings contained in this map.
boolean equals (Object o) Compares the specified object with this map for equality.
Object get (Object key) Returns the value to which this map maps the specified key.
int hashCode () Returns the hash code value for this map.
Set keySet () Returns a set view of the keys contained in this map.
Object put (Object key, Object value) Associates the specified value with the specified key in this map.
void putAll (Map t) Copies all of the mappings from the specified map to this map.
Object remove (Object key) Removes the mapping for this key from this map if present.
Collection values () Returns a collection view of the values contained in this map.
233
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: SortedMap Interface – Methods
Comparator comparator () Returns the comparator associated with this sorted map, or
null if it uses its keys' natural ordering.
Object firstKey () Returns the first (lowest) key currently in this sorted map.
SortedMap headMap (Object toKey) Returns a view of the portion of this sorted map whose
keys are strictly less than toKey.
Object lastKey () Returns the last (highest) key currently in this sorted map.
SortedMap subMap (Object fromKey, Object toKey) Returns a view of the portion of this sorted map whose
keys range from fromKey, inclusive, to toKey, exclusive.
SortedMap tailMap (Object fromKey) Returns a view of the portion of this sorted map whose
keys are greater than or equal to fromKey.
234
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Collection Hierarchy Implementations
235
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Collection Concrete Implementations
Set
HashSet
• much faster than TreeSet (constant time vs. log time for most operations), but offers no ordering guarantees
• iteration is linear in the sum of the number of entries and the number of buckets (the capacity)
• default initial capacity is 101
• one other "tuning parameter" called the load factor
TreeSet
• Implements the SortedSet interface
List
ArrayList
• positional access is constant time
• adding elements to the beginning of the List, or iterating over the List deleting elements from its interior are linear
time operations
• it can take advantage of the native method System.arraycopy when it has to move multiple elements at once
LinkedList
• positional access is linear time
• adding elements to the beginning of the List, or iterating over the List deleting elements from its interior are
constant time operations
Map
HashMap
• much faster than TreeMap (constant time vs. log time for most operations), but offers no ordering guarantees
• iteration is linear in the sum of the number of entries and the number of buckets (the capacity)
• default initial capacity is 101
• one other "tuning parameter" called the load factor
TreeMap
• Implements the SortedMap interface 236
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: ArrayList Class – Constructors and Methods
237
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: ArrayList Class – Methods
Methods inherited from class java.util.AbstractList Methods inherited from class java.util.AbstractCollection
equals, hashCode, iterator, listIterator, subList containsAll, remove, removeAll, retainAll, toString
238
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: ArrayList Class (1)
1 // CollectionTest.java
2 // Using the Collection interface.
3 import java.awt.Color;
4 import java.util.*;
5
6 public class CollectionTest {
7 private static final String colors[] = { "red", "white", "blue" };
8
9 // create ArrayList, add objects to it and manipulate it
10 public CollectionTest()
11 {
12 List list = new ArrayList();
13
14 // add objects to list
15 list.add( Color.magenta ); // add a color object
16
17 for ( int count = 0; count < colors.length; count++ )
18 list.add( colors[ count ] );
19
20 list.add( Color.cyan ); // add a color object
21
239
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: ArrayList Class (2)
240
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: ArrayList Class (3)
39 // remove String objects from Collection
40 private void removeStrings( Collection collection )
41 {
42 Iterator iterator = collection.iterator(); // get iterator
43
44 // loop while collection has items
45 while ( iterator.hasNext() )
46
47 if ( iterator.next() instanceof String )
48 iterator.remove(); // remove String object
49 }
50
51 public static void main( String args[] )
52 {
53 new CollectionTest();
54 }
55
56 } // end class CollectionTest
ArrayList:
java.awt.Color[r=255,g=0,b=255] red white blue java.awt.Color
[r=0,g=255,b=255]
242
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: LinkedList Class – Methods
Object getLast () Returns the last element in this list.
int indexOf (Object o) Returns the index in this list of the first occurrence of the specified element,
or -1 if the List does not contain this element.
int lastIndexOf (Object o) Returns the index in this list of the last occurrence of the specified element,
or -1 if the list does not contain this element.
ListIterator listIterator (int index) Returns a list-iterator of the elements in this list (in proper sequence), starting
at the specified position in the list.
Object remove (int index) Removes the element at the specified position in this list.
boolean remove (Object o) Removes the first occurrence of the specified element in this list.
Object removeFirst () Removes and returns the first element from this list.
Object removeLast () Removes and returns the last element from this list.
Object set (int index, Object element) Replaces the element at the specified position in this list with the specified
element.
int size () Returns the number of elements in this list.
Object[] toArray () Returns an array containing all of the elements in this list in the correct order.
Object[] toArray (Object[] a) Returns an array containing all of the elements in this list in the correct order.
The runtime type of the returned array is that of the specified array.
Methods inherited from class java.util.AbstractList Methods inherited from class java.util.AbstractCollection
equals, hashCode, listIterator, removeRange, subList containsAll, isEmpty, removeAll, retainAll, toString
243
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: LinkedList Class (1)
1 // ListTest.java
2 // Using LinkLists.
3 import java.util.*;
4
5 public class ListTest {
6 private static final String colors[] = { "black", "yellow",
7 "green", "blue", "violet", "silver" };
8 private static final String colors2[] = { "gold", "white",
9 "brown", "blue", "gray", "silver" };
10
11 // set up and manipulate LinkedList objects
12 public ListTest()
13 {
14 List link = new LinkedList();
15 List link2 = new LinkedList();
16
17 // add elements to each list
18 for ( int count = 0; count < colors.length; count++ ) {
19 link.add( colors[ count ] );
20 link2.add( colors2[ count ] ); Use LinkedList method addAll
21 }
to append link2 elements to link
22
23 link.addAll( link2 ); // concatenate lists
24 link2 = null; // release resources
Nullify link2, so it can be garbage collected
25 244
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: LinkedList Class (2)
26 printList( link );
27
28 uppercaseStrings( link );
29
30 printList( link );
31
32 System.out.print( "\nDeleting elements 4 to 6..." );
33 removeItems( link, 4, 7 );
34
35 printList( link );
36
37 printReversedList( link );
38
39 } // end constructor ListTest
40
41 // output List contents
42 public void printList( List list )
43 {
44 System.out.println( "\nlist: " );
45
46 for ( int count = 0; count < list.size(); count++ )
47 System.out.print( list.get( count ) + " " );
48
Use List method get to obtain object
49 System.out.println();
50 }
in LinkedList, then print its value
245
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: LinkedList Class (3)
51
52 // locate String objects and convert to uppercase
Use ListIterator to
53 private void uppercaseStrings( List list ) traverse LinkedList
54 { elements and convert
55 ListIterator iterator = list.listIterator(); them to upper case (if
56 elements are Strings)
57 while ( iterator.hasNext() ) {
58 Object object = iterator.next(); // get item
59
60 if ( object instanceof String ) // check for String
61 iterator.set( ( ( String ) object ).toUpperCase() );
62 }
63 }
64
65 // obtain sublist and use clear method to delete sublist items
66 private void removeItems( List list, int start, int end )
67 {
68 list.subList( start, end ).clear(); // remove items
69 }
70
Use List methods subList and clear
71 // print reversed list to remove LinkedList elements
72 private void printReversedList( List list )
73 {
74 ListIterator iterator = list.listIterator( list.size() );
75 246
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: LinkedList Class (4)
ListIterator method
76 System.out.println( "\nReversed List:" ); hasPrevious determines
77
whether the ListIterator
78 // print list in reverse order
contains more elements
79 while( iterator.hasPrevious() )
80 System.out.print( iterator.previous() + " " );
81 }
82 ListIterator method previous
83 public static void main( String args[] ) returns previous Object in
84 { ListIterator
85 new ListTest();
86 }
87
88 } // end class ListTest
list:
black yellow green blue violet silver gold white brown blue gray silver
list:
BLACK YELLOW GREEN BLUE VIOLET SILVER GOLD WHITE BROWN BLUE GRAY SILVER
Reversed List:
SILVER GRAY BLUE BROWN WHITE BLUE GREEN YELLOW BLACK 247
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: HashSet Class – Constructors and Methods
HashSet () Constructs a new, empty set; the backing HashMap instance has
default capacity and load factor, which is 0.75.
HashSet (Collection c) Constructs a new set containing the elements in the specified
collection.
HashSet (int initialCapacity) Constructs a new, empty set; the backing HashMap instance has
the specified initial capacity and default load factor, which is
0.75.
HashSet (int initialCapacity, float loadFactor) Constructs a new, empty set; the backing HashMap instance has
the specified initial capacity and the specified load factor.
boolean add (Object o) Adds the specified element to this set if it is not already present.
void clear () Removes all of the elements from this set.
Object clone () Returns a shallow copy of this HashSet instance: the elements
themselves are not cloned.
boolean contains (Object o) Returns true if this set contains the specified element.
boolean isEmpty () Returns true if this set contains no elements.
Iterator iterator () Returns an iterator over the elements in this set.
boolean remove (Object o) Removes the given element from this set if it is present.
int size () Returns the number of elements in this set (its cardinality).
Methods inherited from class java.util.AbstractSet Methods inherited from class java.util.AbstractCollection
equals, hashCode, removeAll addAll, containsAll, retainAll, toArray, toArray, toString
248
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: HashSet Class (1)
1 // SetTest.java
2 // Using a HashSet to remove duplicates.
3 import java.util.*;
4
5 public class SetTest {
6 private static final String colors[] = { "red", "white", "blue",
7 "green", "gray", "orange", "tan", "white", "cyan",
8 "peach", "gray", "orange" };
9 Use static method asList
10 // create and output ArrayList of class Arrays to return
11 public SetTest() List view of array colors
12 {
13 List list = new ArrayList( Arrays.asList( colors ) );
14 System.out.println( "ArrayList: " + list );
15 printNonDuplicates( list );
16 }
17
18 // create set from array to eliminate duplicates
19 private void printNonDuplicates( Collection collection )
20 {
21 // create a HashSet and obtain its iterator
22 Set set = new HashSet( collection );
23 Iterator iterator = set.iterator(); HashSet from
Create
24 Collection object
25 System.out.println( "\nNonduplicates are: " ); 249
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: HashSet Class (2)
27 while ( iterator.hasNext() )
28 System.out.print( iterator.next() + " " );
29
30 System.out.println();
31 }
32
33 public static void main( String args[] )
34 {
35 new SetTest();
36 }
37
38 } // end class SetTest
ArrayList: [red, white, blue, green, gray, orange, tan, white, cyan,
peach, gray, orange]
Nonduplicates are:
red cyan white tan gray green orange blue peach
250
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: TreeSet Class – Constructors and Methods
TreeSet () Constructs a new, empty set, sorted according to the elements' natural order.
TreeSet (Collection c) Constructs a new set containing the elements in the specified collection,
sorted according to the elements' natural order.
TreeSet (Comparator c) Constructs a new empty set, sorted according to the given comparator.
TreeSet (SortedSet s) Constructs a new set containing the same elements as the given sorted set,
sorted according to the same ordering.
boolean add (Object o) Adds the specified element to this set if it is not already present.
boolean addAll (Collection c) Adds all of the elements in the specified collection to this set if they're not
already present.
void clear () Removes all of the elements from this set.
Object clone () Returns a shallow copy of this TreeSet instance.
Comparator comparator() Returns the comparator used to order this sorted set, or null if this tree set
uses its elements natural ordering.
boolean contains (Object elem) Returns true if this set contains the specified element.
Object first () Returns the first (lowest) element currently in this sorted set.
SortedSet headSet (Object toElement) Returns a view of the portion of this set whose elements are strictly less than
toElement.
251
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: TreeSet Class – Methods
Methods inherited from class java.util.AbstractSet Methods inherited from class java.util.AbstractCollection
equals, hashCode, removeAll containsAll, retainAll, toArray, toArray, toString
252
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: TreeSet Class (1)
1 // SortedSetTest.java
2 // Using TreeSet and SortedSet.
3 import java.util.*;
4
5 public class SortedSetTest {
6 private static final String names[] = { "yellow", "green",
7 "black", "tan", "grey", "white", "orange", "red", "green" };
8
9 // create a sorted set with TreeSet, then manipulate it
10 public SortedSetTest()
11 {
12 SortedSet tree = new TreeSet( Arrays.asList( names ) );
14 System.out.println( "set: " );
15 printSet( tree );
17 // get headSet based upon "orange"
18 System.out.print( "\nheadSet (\"orange\"): " ); Use TreeSet method
19 printSet( tree.headSet( "orange" ) ); headSet to get TreeSet
21 // get tailSet based upon "orange"
subset less than "orange"
22 System.out.print( "tailSet (\"orange\"): " );
23 printSet( tree.tailSet( "orange" ) ); Use TreeSet method
25 // get first and last elements
tailSet to get TreeSet
26 System.out.println( "first: " + tree.first() );
27 System.out.println( "last : " + tree.last() );
subset greater than "orange"
28 }
253
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: TreeSet Class (2)
30 // output set
31 private void printSet( SortedSet set )
32 {
33 Iterator iterator = set.iterator();
34
35 while ( iterator.hasNext() )
36 System.out.print( iterator.next() + " " );
37
38 System.out.println();
39 }
40
41 public static void main( String args[] )
42 {
43 new SortedSetTest();
44 }
45
46 } // end class SortedSetTest
set:
black green grey orange red tan white yellow
HashMap () Constructs a new, empty map with a default capacity and load
factor, which is 0.75.
HashMap (int initialCapacity) Constructs a new, empty map with the specified initial
capacity and default load factor, which is 0.75.
HashMap (int initialCapacity, float loadFactor) Constructs a new, empty map with the specified initial
capacity and the specified load factor.
HashMap (Map t) Constructs a new map with the same mappings as the given
map.
void clear () Removes all mappings from this map.
Object clone () Returns a shallow copy of this HashMap instance: the keys
and values themselves are not cloned.
boolean containsKey (Object key) Returns true if this map contains a mapping for the specified
key.
boolean containsValue (Object value) Returns true if this map maps one or more keys to the
specified value.
255
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: HashMap Class – Methods
Set entrySet () Returns a set view of the mappings contained in this map.
Object get (Object key) Returns the value to which this map maps the specified key.
boolean isEmpty () Returns true if this map contains no key-value mappings.
Set keySet () Returns a set view of the keys contained in this map.
Object put (Object key, Object value) Associates the specified value with the specified key in this map.
void putAll (Map t) Copies all of the mappings from the specified map to this map.
Object remove (Object key) Removes the mapping for this key from this map if present.
int size () Returns the number of key-value mappings in this map.
Collection values () Returns a collection view of the values contained in this map.
256
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: HashMap Class (1)
1 // MapTest.java
2 // Using a HashMap to store the number of words that begin with a given letter
3
4 import java.util.*;
5
6 public class MapTest {
7 private static String names[] = { "one“ , "two“ , "three“ , "four“ , "five“ ,
8 "two“ , "ten“ , "four“ };
9
10 public MapTest()
11 {
12 HashMap map = new HashMap();
13 Integer i;
15 Character c;
16
17 for ( int count = 0; count< names.length; count++ ) {
18 c = new Character( names[count].charAt( 0 ) );
19 i = ( Integer ) map.get( c );
20
21 if ( i == null )
22 map.put( c , new Integer( 1 ) );
23 else
24 map.put( c , new Integer( i.intValue() + 1 ) );
25 }
26 System.out.println( "\nnumber of words beginning with each letter: “ );
27 printMap( map );
28 } 257
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: HashMap Class (2)
29 // output map contents
30 public void printMap( Map mapRef )
31 {
32 System.out.println( mapRef.toString() );
33 System.out.println( "size: " + mapRef.size()) ;
34 System.out.println( "isEmpty: " + mapRef.isEmpty() );
35 }
36
37 public static void main( String args[] )
38 {
39 new MapTest();
40 }
41
42 } // endclass MapTest
258
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: TreeMap Class – Constructors and Methods
TreeMap () Constructs a new, empty map, sorted according to the keys' natural order.
TreeMap (Comparator c) Constructs a new, empty map, sorted according to the given comparator.
TreeMap (Map m) Constructs a new map containing the same mappings as the given map,
sorted according to the keys' natural order.
TreeMap (SortedMap m) Constructs a new map containing the same mappings as the given
SortedMap, sorted according to the same ordering.
void clear () Removes all mappings from this TreeMap.
Object clone () Returns a shallow copy of this TreeMap instance.
Comparator comparator () Returns the comparator used to order this map, or null if this map uses its
keys' natural order.
boolean containsKey (Object key) Returns true if this map contains a mapping for the specified key.
boolean containsValue (Object value) Returns true if this map maps one or more keys to the specified value.
Set entrySet () Returns a set view of the mappings contained in this map.
Object firstKey () Returns the first (lowest) key currently in this sorted map.
Object get (Object key) Returns the value to which this map maps the specified key.
SortedMap headMap (Object toKey) Returns a view of the portion of this map whose keys are strictly less than
toKey.
259
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: TreeMap Class – Methods
Set keySet () Returns a set view of the keys contained in this map.
Object lastKey () Returns the last (highest) key currently in this sorted map.
Object put (Object key, Object value) Associates the specified value with the specified key in this
map.
void putAll (Map t) Copies all of the mappings from the specified map to this map.
Object remove (Object key) Removes the mapping for this key from this TreeMap if
present.
int size () Returns the number of key-value mappings in this map.
SortedMap subMap (Object fromKey, Object toKey) Returns a view of the portion of this map whose keys range
from fromKey, inclusive, to toKey, exclusive.
SortedMap tailMap (Object fromKey) Returns a view of the portion of this map whose keys are
greater than or equal to fromKey.
Collection values () Returns a collection view of the values contained in this map.
260
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Collection Algorithms
Collection algorithms
min
• returns the minimum element contained in a specified Collection
max
• returns the maximum element contained in a specified Collection
List algorithms
sort
• reorders a List so that its elements are ascending order according to some ordering relation
• uses a slightly optimized merge sort algorithm
binarySearch
• searches for a specified element in a sorted List using the binary search algorithm
reverse
• reverses the order of the elements in a List
shuffle
• destroys any trace of order that may have been present in a List, such that all possible
permutations occur with equal likelihood
fill
• overwrites every element in a List with the specified value
copy
• copies the elements of a source List into a destination List , overwriting its contents
• the destination List must be at least as long as the source
• if it is longer, the remaining elements in the destination List are unaffected 261
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Collections Class – Methods (1)
static int binarySearch (List list, Object key) Searches the specified list for the specified object using
the binary search algorithm.
static int binarySearch (List list, Object key, Comparator c) Searches the specified list for the specified object using
the binary search algorithm. The list must be sorted into
ascending order according to the specified comparator.
static void copy (List dest, List src) Copies all of the elements from one list into another.
static void fill (List list, Object o) Replaces all of the elements of the specified list with the
specified element.
static Object max (Collection coll) Returns the maximum element of the given collection,
according to the natural ordering of its elements.
static Object max (Collection coll, Comparator comp) Returns the maximum element of the given collection,
according to the order induced by the specified
comparator.
static Object min (Collection coll) Returns the minimum element of the given collection,
according to the natural ordering of its elements.
static Object min (Collection coll, Comparator comp) Returns the minimum element of the given collection,
according to the order induced by the specified
comparator.
262
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Collections Class – Methods (2)
static void reverse (List list) Reverses the order of the elements in the specified list.
static Comparator reverseOrder () Returns a comparator that imposes the reverse of the natural
ordering on a collection of objects that implement the Comparable
interface.
static void shuffle (List list) Randomly permutes the specified list using a default source of
randomness.
static void shuffle (List list, Random rnd) Randomly permute the specified list using the specified source of
randomness.
static void sort (List list) Sorts the specified list into ascending order, according to the natural
ordering of its elements.
static void sort (List list, Comparator c) Sorts the specified list according to the order induced by the
specified comparator.
263
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Collections Class (1)
1 // CollectionsTest.java
2 // Using the Collections class.
3 import java.awt.Color;
4 import java.util.*;
5
6 public class CollectionsTest {
7 private static final String colors[] = { "red ", "white", "blue",
"green", "yellow", "black", "orange" };
8
9 // create ArrayList, add objects to it and manipulate it
10 public CollectionsTest()
11 {
12 List list = new ArrayList();
13
14 for ( int count = 0; count < colors.length; count++ )
15 list.add( colors[ count ] );
16
17 System.out.println( "\nArrayList: " );
18 for ( int count = 0; count < list.size(); count++ )
19 System.out.print( list.get( count ) + " " );
20
21 // find min and max
22 System.out.println( "\n\nArrayList min: " + Collections.min( list ) +
"\nArrayList max: " + Collections.max( list ) );
264
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Collections Class (2)
23 // sort list
24 Collections.sort( list );
25
26 System.out.println( "\nArrayList after sorting: " );
27 for ( int count = 0; count < list.size(); count++ )
28 System.out.print( list.get( count ) + " " );
29
30 // search for elements
31 System.out.println( "\n\nSearching for white: " +
Collections.binarySearch( list, "white" ) );
32
33 System.out.println( "\nSearching for brown: " +
Collections.binarySearch(list, "brown" ) );
34
35 // shuffle list
36 Collections.shuffle( list );
37
38 System.out.println( "\nArrayList after shuffling: " );
39 for ( int count = 0; count < list.size(); count++ )
40 System.out.print( list.get( count ) + " " );
41
265
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Collections Class (3)
42 // reverse list
43 Collections.reverse( list );
44
45 System.out.println( "\n\nArrayList after reversing: " );
46 for ( int count = 0; count < list.size(); count++ )
47 System.out.print( list.get( count ) + " " );
48
49 } // end constructor CollectionsTest
50
51 public static void main( String args[] )
52 {
53 new CollectionsTest();
54 }
55
56 } // end class CollectionsTest
266
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Collections Class (4)
ArrayList:
red white blue green yellow black orange
Stream Classes:
268
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Files and Streams (1)
Sally Black
Tom Blue
Judy Green
File
Iris Orange
Randy Red
Judy Green
Record
Judy Field
1 Bit
269
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Files and Streams (2)
Java views a file as a stream of bytes
File ends with end-of-file marker or a specific byte
number
File as a stream of bytes associated with an object
• Java also associates streams with devices
• System.in, System.out, and System.err
• Streams can be redirected
Buffering
Improves performance of I/O
Copies each output to a region of memory called a
buffer
Entire buffer output to disk at once
• One long disk access takes less time than many smaller ones
BufferedOutputStream buffers file output
BufferedInputStream buffers file input
271
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: I/O Character Streams
272
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: I/O Byte Streams
273
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: File Class – Constructors and Methods
File
An abstract representation of file and directory pathnames
File (File parent, String child) Creates a new File instance from a parent abstract
pathname and a child pathname string.
File (String pathname) Creates a new File instance by converting the given
pathname string into an abstract pathname.
File (String parent, String child) Creates a new File instance from a parent pathname
string and a child pathname string.
boolean createNewFile () Atomically creates a new, empty file named by this
abstract pathname if and only if a file with this name
does not yet exist.
boolean delete () Deletes the file or directory denoted by this abstract
pathname.
boolean mkdir () Creates the directory named by this abstract pathname.
boolean renameTo (File dest) Renames the file denoted by this abstract pathname.
274
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: File Class - Methods
Method Description
boolean canRead() Returns true if a file is readable; false otherwise.
boolean canWrite() Returns true if a file is writable; false otherwise.
boolean exists() Returns true if the name specified as the argument to the File
constructor is a file or directory in the specified path; false
otherwise.
boolean isFile() Returns true if the name specified as the argument to the File
constructor is a file; false otherwise.
boolean isDirectory() Returns true if the name specified as the argument to the File
constructor is a directory; false otherwise.
boolean isAbsolute() Returns true if the arguments specified to the File constructor
indicate an absolute path to a file or directory; false otherwise.
String getAbsolutePath() Returns a string with the absolute path of the file or directory.
String getName() Returns a string with the name of the file or directory.
String getPath() Returns a string with the path of the file or directory.
String getParent() Returns a string with the parent directory of the file or directory-that
is, the directory in which the file or directory can be found.
long length() Returns the length of the file, in bytes. If the File object
represents a directory, 0 is returned.
long lastModified() Returns a platform-dependent representation of the time at which
the file or directory was last modified. The value returned is useful
only for comparison with other values returned by this method.
String[] list() Returns an array of strings representing the contents of a directory.
Returns null if the File object is not a directory. 275
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Creating a new directory
try {
File dir;
boolean itWorked;
276
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reading/Writing characters
FileReader and FileWriter can read/write a file
one character at a time
import java.io.*;
public class Copy {
public static void main(String[] args) throws IOException {
File inputFile = new File( “source.txt“ );
File outputFile = new File( “destination.txt“ );
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
}
}
277
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reading/Writing bytes
FileInputStream and FileOutputStream can
read/write a file one byte at a time
import java.io.*;
public class CopyBytes {
public static void main(String[] args) throws IOException {
File inputFile = new File( “source.txt“ );
File outputFile = new File( “destination.txt“ );
FileInputStream in = new FileInputStream(inputFile);
FileOutputStream out = new FileOutputStream(outputFile);
int b;
while ((b = in.read()) != -1)
out.write(b);
in.close();
out.close();
}
}
278
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Data Input/Output Stream
279
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing primitive data to a Stream
Basic Algorithm
Open the file for output by instantiating the appropriate streams
Call write methods to transfer data
Flush the stream
Close the stream
try {
FileOutputStream fStream;
DataOutputStream writingStream;
fStream = new FileOutputStream( “oneFile.bin” );
writingStream = new DataOutputStream( fStream );
writingStream.writeDouble( 3.14159 );
writingStream.writeInt( 7 );
writingStream.writeChar( “Z” );
writingStream.flush();
writingStream.close();
}
catch (IOException e) {
System.out.println( “I/O exception” );
}
280
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reading primitive data from a Stream
Basic Algorithm
Open the file for input by instantiating the appropriate streams
Call read methods to transfer data
Close the stream
try {
double val1;
int val2;
char val3;
FileInputStream fStream;
DataInputStream inStream;
fStream = new FileInputStream( “oneFile.bin” );
inStream = new DataInputStream( fStream );
val1 = inStream.readDouble();
val2 = inStream.readInt();
val3 = inStream.readChar();
inStream.close();
}
catch (IOException e) {
System.out.println( “I/O exception” );
} 281
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing text
PrintWriter print formatted representations of objects to a
text-output stream
try {
FileOutputStream fStream;
PrintWriter myStream;
fStream = new FileOutputStream( “threeLines.txt” );
myStream = new PrintWriter( fStream );
myStream.println( “This is line #1.” );
myStream.println( “This is line #2.” );
myStream.print( “This is the start,” );
myStream.println( “ and this is the end of line #3.” );
myStream.flush();
myStream.close();
}
catch (IOException e) {
System.out.println( “I/O exception” );
}
282
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reading text
BufferedReader read text from a character-input stream,
buffering characters so as to provide for the efficient reading of
characters, arrays, and lines
try {
FileReader fReader;
BufferedReader reader;
String line;
fReader = new FileReader( “threeLines.txt” );
reader = new BufferedReader( fReader );
line = reader.readLine();
while ( line != null ) {
System.out.println( line ); //echoes input to standard out
line = reader.readLine();
}
reader.close();
}
catch (IOException e) {
System.out.println( “I/O exception” );
}
283
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Object Serialization (1)
An object can be converted into a simple stream of bytes in such a
way that it can be reconstructed correctly later (permanent object)
Once we have such a stream of bytes, we can output it to a file and
read it back again
// Write the object out
ObjectOutputStream outstream =
new ObjectOutputStream(outputStreamObject);
outstream.writeObject(theObject);
outstream.close();
public Manager(String n, double s, int year, int month, int day, double b) {
super(n, s, year, month, day);
bonus = b;
}
}
285
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Object Serialization (3)
class ObjectFileTest {
public static void main(String[] args) {
Manager boss = new Manager( "Carl Cracker" , 80000, 1987, 12, 15, 5000);
Employee[] staff = new Employee[3];
staff[0] = boss;
staff[1] = new Employee( "Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee( "Tony Tester" , 40000, 1990, 3, 15);
try {
// save all employee records to the file employee.dat
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.dat"));
out.writeObject(staff);
out.close();
// retrieve all records into a new array
ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.dat"));
Employee[] newStaff = (Employee[])in.readObject();
in.close();
// print the newly read employee records
for (int i = 0; i < newStaff.length; i++)
System.out.println(newStaff[i]);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
286
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: File Class (1)
1 // FileTest.java
2 // Demonstrating the File class.
3 import java.awt.*;
4 import java.awt.event.*;
5 import java.io.*;
Import java.io
6 import javax.swing.*;
package
7
8 public class FileTest extends JFrame
9 implements ActionListener {
10
11 private JTextField enterField;
12 private JTextArea outputArea;
13
14 // set up GUI
15 public FileTest()
16 {
17 super( "Testing class File" );
18
19 enterField = new JTextField( "Enter file or directory name here" );
20 enterField.addActionListener( this );
21 outputArea = new JTextArea();
22
23 ScrollPane scrollPane = new ScrollPane();
24 scrollPane.add( outputArea );
25 287
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: File Class (2)
26 Container container = getContentPane();
27 container.add( enterField, BorderLayout.NORTH );
28 container.add( scrollPane, BorderLayout.CENTER );
29
30 setSize( 400, 400 );
31 setVisible( true );
32
33 } // end constructor
34
35 // display information about file user specifies
36 public void actionPerformed( ActionEvent actionEvent ) create a new File
37 { and assign it to name
38 File name = new File( actionEvent.getActionCommand() );
39 Body of if outputs
40 // if name exists, output information about it information about the
41 if ( name.exists() ) { file if it exists
42 outputArea.setText( name.getName() + " exists\n" +
43 ( name.isFile() ? "is a file\n" : "is not a file\n" ) +
44 ( name.isDirectory() ? "is a directory\n" :
45 "is not a directory\n" ) +
46 ( name.isAbsolute() ? "is absolute path\n" :
47 "is not absolute path\n" ) + "Last modified: " +
48 name.lastModified() + "\nLength: " + name.length() +
49 "\nPath: " + name.getPath() + "\nAbsolute path: " +
50 name.getAbsolutePath() + "\nParent: " + name.getParent() ); 288
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: File Class (3)
52 // output information if name is a file
53 if ( name.isFile() ) {
54
Test if our object is a
55 // append contents of file to outputArea file
56 try {
57 BufferedReader input = new BufferedReader(
58 new FileReader( name ) ); Create reader to gather
59 StringBuffer buffer = new StringBuffer(); data from the file
60 String text;
61 outputArea.append( "\n\n" );
62
63 while ( ( text = input.readLine() ) != null )
64 buffer.append( text + "\n" );
Read text until there is
65
66 outputArea.append( buffer.toString() );
no more in the file
67 }
68
69 // process file processing problems
70 catch ( IOException ioException ) {
71 JOptionPane.showMessageDialog( this, "FILE ERROR",
72 "FILE ERROR", JOptionPane.ERROR_MESSAGE );
73 }
74
75 } // end if
289
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: File Class (4)
77 // output directory listing
78 else if ( name.isDirectory() ) {
79 String[] directory = name.list();
80 Get a list of the files
81 outputArea.append( "\n\nDirectory contents:\n"); in the directory
82
83 for ( int i = 0; i < directory.length; i++ )
84 outputArea.append( directory[ i ] + "\n" );
85 }
87 } // end outer if
88
89 // not file or directory, output error message If file does not exist,
90 else { display error
91 JOptionPane.showMessageDialog( this,
92 actionEvent.getActionCommand() + " Does Not Exist",
93 "ERROR", JOptionPane.ERROR_MESSAGE );
94 }
96 } // end method actionPerformed
97
98 public static void main( String args[] )
99 {
100 FileTest application = new FileTest();
101 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
102 }
103 } // end class FileTest 290
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: File Class (5)
291
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (1)
1 // BankUI.java
2 // A reusable GUI for the examples in this chapter.
3 package com;
4 Compile this class in
5 import java.awt.*; a package for reuse
6 import javax.swing.*;
7
Bank GUI for all
8 public class BankUI extends JPanel {
9
examples in this
10 // label text for GUI chapter
11 protected final static String names[] = { "Account number",
12 "First name", "Last name", "Balance", "Transaction Amount" };
13
14 // GUI components; protected for future subclass access
15 protected JLabel labels[];
These buttons will
16 protected JTextField fields[];
17 protected JButton doTask1, doTask2;
perform actions in
18 protected JPanel innerPanelCenter, innerPanelSouth; later examples
19
20 protected int size; // number of text fields in GUI
21
22 // constants representing text fields in GUI
23 public static final int ACCOUNT = 0, FIRSTNAME = 1, LASTNAME = 2,
24 BALANCE = 3, TRANSACTION = 4;
25 292
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (2)
26 // Set up GUI. Constructor argument size determines the number of
27 // rows of GUI components.
28 public BankUI( int mySize )
29 {
30 size = mySize;
31 labels = new JLabel[ size ];
32 fields = new JTextField[ size ];
33
34 // create labels
35 for ( int count = 0; count < labels.length; count++ )
36 labels[ count ] = new JLabel( names[ count ] );
37
38 // create text fields
39 for ( int count = 0; count < fields.length; count++ )
40 fields[ count ] = new JTextField();
41
42 // create panel to lay out labels and fields
43 innerPanelCenter = new JPanel();
44 innerPanelCenter.setLayout( new GridLayout( size, 2 ) );
45
46 // attach labels and fields to innerPanelCenter
47 for ( int count = 0; count < size; count++ ) {
48 innerPanelCenter.add( labels[ count ] );
49 innerPanelCenter.add( fields[ count ] );
50 } 293
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (3)
52 // create generic buttons; no labels or event handlers
53 doTask1 = new JButton();
54 doTask2 = new JButton();
56 // create panel to lay out buttons and attach buttons
57 innerPanelSouth = new JPanel();
58 innerPanelSouth.add( doTask1 );
59 innerPanelSouth.add( doTask2 );
61 // set layout of this container and attach panels to it
62 setLayout( new BorderLayout() );
63 add( innerPanelCenter, BorderLayout.CENTER );
64 add( innerPanelSouth, BorderLayout.SOUTH );
66 validate(); // validate layout
68 } // end constructor
69
70 // return reference to generic task button doTask1
71 public JButton getDoTask1Button()
72 {
73 return doTask1;
74 }
75 Return the task
76 // return reference to generic task button doTask2
buttons
77 public JButton getDoTask2Button()
78 {
79 return doTask2;
80 } 294
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (4)
82 // return reference to fields array of JTextFields
83 public JTextField[] getFields()
84 {
85 return fields;
86 }
87
88 // clear content of text fields
89 public void clearFields()
90 {
91 for ( int count = 0; count < size; count++ )
92 fields[ count ].setText( "" );
93 }
94
95 // set text field values; throw IllegalArgumentException if
96 // incorrect number of Strings in argument
97 public void setFieldValues( String strings[] )
98 throws IllegalArgumentException
99 {
100 if ( strings.length != size )
101 throw new IllegalArgumentException( "There must be " +
102 size + " Strings in the array" );
103
104 for ( int count = 0; count < size; count++ )
105 fields[ count ].setText( strings[ count ] );
106 } 295
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (5)
107
108 // get array of Strings with current text field contents
109 public String[] getFieldValues()
110 {
111 String values[] = new String[ size ];
112
113 for ( int count = 0; count < size; count++ )
114 values[ count ] = fields[ count ].getText();
115
116 return values;
117 }
118
119 } // end class BankUI
296
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (6)
1 // AccountRecord.java
2 // A class that represents one record of information.
3 package com; Compile this class in
5 import java.io.Serializable; a package for reuse
6
7 public class AccountRecord implements Serializable {
8 private int account; Implements Serializable
9 private String firstName; so AccountRecords can be
10 private String lastName;
used with input and output
11 private double balance;
streams
12
13 // no-argument constructor calls other constructor with default values
14 public AccountRecord()
15 {
16 this( 0, "", "", 0.0 );
17 }
18
19 // initialize a record
20 public AccountRecord( int acct, String first, String last, double bal )
21 {
22 setAccount( acct );
23 setFirstName( first );
24 setLastName( last );
25 setBalance( bal );
26 } 297
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (7)
28 // set account number
29 public void setAccount( int acct )
30 {
31 account = acct;
32 }
33
34 // get account number
35 public int getAccount()
36 {
37 return account;
38 }
39
40 // set first name
41 public void setFirstName( String first )
42 {
43 firstName = first;
44 }
45
46 // get first name
47 public String getFirstName()
48 {
49 return firstName;
50 }
51
298
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (8)
52 // set last name
53 public void setLastName( String last )
54 {
55 lastName = last;
56 }
57
58 // get last name
59 public String getLastName()
60 {
61 return lastName;
62 }
63
64 // set balance
65 public void setBalance( double bal )
66 {
67 balance = bal;
68 }
69
70 // get balance
71 public double getBalance()
72 {
73 return balance;
74 }
75
76 } // end class AccountRecord 299
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (9)
1 // CreateSequentialFile.java
2 // Writing objects sequentially to a file with class ObjectOutputStream.
3 import java.io.*;
4 import java.awt.*;
5 import java.awt.event.*;
6 import javax.swing.*; Import our GUI class
8 import com.BankUI; and record class
9 import com.AccountRecord;
10
11 public class CreateSequentialFile extends JFrame {
12 private ObjectOutputStream output;
13 private BankUI userInterface;
14 private JButton enterButton, openButton;
16 // set up GUI
17 public CreateSequentialFile()
18 {
19 super( "Creating a Sequential File of Objects" ); Create our interface
20 and get a reference to
21 // create instance of reusable user interface
the first task button
22 userInterface = new BankUI( 4 ); // four textfields
23 getContentPane().add( userInterface, BorderLayout.CENTER );
24
25 // configure button doTask1 for use in this program
26 openButton = userInterface.getDoTask1Button();
27 openButton.setText( "Save into File ..." ); 300
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (10)
28
29 // register listener to call openFile when button pressed
30 openButton.addActionListener(
31
32 // anonymous inner class to handle openButton event
33 new ActionListener() {
34
35 // call openFile when button pressed
36 public void actionPerformed( ActionEvent event )
37 {
38 openFile();
39 }
40
41 } // end anonymous inner class
42
43 ); // end call to addActionListener
44
45 // configure button doTask2 for use in this program
46 enterButton = userInterface.getDoTask2Button();
47 enterButton.setText( "Enter" ); Get a reference to the
48 enterButton.setEnabled( false ); // disable button
second task button
49
50 // register listener to call addRecord when button pressed
51 enterButton.addActionListener(
52 301
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (11)
53 // anonymous inner class to handle enterButton event
54 new ActionListener() {
55
56 // call addRecord when button pressed
57 public void actionPerformed( ActionEvent event )
58 {
59 addRecord();
60 }
62 } // end anonymous inner class
64 ); // end call to addActionListener
65
66 // register window listener to handle window closing event
67 addWindowListener(
68
69 // anonymous inner class to handle windowClosing event
70 new WindowAdapter() {
71
72 // add current record in GUI to file, then close file
73 public void windowClosing( WindowEvent event )
74 {
75 if ( output != null )
76 addRecord();
78 closeFile();
79 }
302
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (12)
81 } // end anonymous inner class
82
83 ); // end call to addWindowListener
84 Instantiate a
85 setSize( 300, 200 ); JFileChooser
86 setVisible( true ); and assign it to
87 fileChooser
88 } // end CreateSequentialFile constructor
89
90 // allow user to specify file name
91 private void openFile()
Constant FILES_ONLY indicates
92 { only files can be selected
93 // display file dialog, so user can choose file to open
94 JFileChooser fileChooser = new JFileChooser();
95 fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
96
Method
97 int result = fileChooser.showSaveDialog( this );
98
showSaveDialog
99 // if user clicked Cancel button on dialog, return causes the
100 if ( result == JFileChooser.CANCEL_OPTION ) JFileChooser
101 return; titled Save to appear
102
103 File fileName = fileChooser.getSelectedFile(); // get selected file
303
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (13)
105 // display error if invalid
106 if ( fileName == null || fileName.getName().equals( "" ) )
107 JOptionPane.showMessageDialog( this, "Invalid File Name",
108 "Invalid File Name", JOptionPane.ERROR_MESSAGE );
109
110 else {
111
112 // open file
113 try { Open selected file
114 output = new ObjectOutputStream(
115 new FileOutputStream( fileName ) );
116
117 openButton.setEnabled( false );
118 enterButton.setEnabled( true );
119 }
120
121 // process exceptions from opening file
122 catch ( IOException ioException ) {
123 JOptionPane.showMessageDialog( this, "Error Opening File",
124 "Error", JOptionPane.ERROR_MESSAGE );
125 }
126
127 } // end else
128
129 } // end method openFile 304
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (14)
131 // close file and terminate application
132 private void closeFile()
133 {
134 // close file
135 try {
136 output.close(); Method closeFile
137 System.exit( 0 ); closes the current file
138 }
139
140 // process exceptions from closing file
141 catch( IOException ioException ) {
142 JOptionPane.showMessageDialog( this, "Error closing file",
143 "Error", JOptionPane.ERROR_MESSAGE );
144 System.exit( 1 );
145 }
146
147 } // end method closeFile
148
149 // add record to file Get the data in the
150 public void addRecord()
textfields
151 {
152 int accountNumber = 0;
153 AccountRecord record;
154 String fieldValues[] = userInterface.getFieldValues();
305
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (15)
156 // if account field value is not empty
157 if ( ! fieldValues[ BankUI.ACCOUNT ].equals( "" ) ) {
158
159 // output values to file
160 try {
161 accountNumber = Integer.parseInt(
162 fieldValues[ BankUI.ACCOUNT ] );
163
Create a new record
164 if ( accountNumber > 0 ) {
166 // create new record
167 record = new AccountRecord( accountNumber,
168 fieldValues[ BankUI.FIRSTNAME ],
169 fieldValues[ BankUI.LASTNAME ],
170 Double.parseDouble( fieldValues[ BankUI.BALANCE ] ) );
172 // output record and flush buffer
173 output.writeObject( record ); Write the record to the file
174 output.flush(); immediately
175 }
177 else {
178 JOptionPane.showMessageDialog( this,
179 "Account number must be greater than 0",
180 "Bad account number", JOptionPane.ERROR_MESSAGE );
181 }
306
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (16)
183 // clear textfields
184 userInterface.clearFields();
185
186 } // end try
187
188 // process invalid account number or balance format
189 catch ( NumberFormatException formatException ) {
190 JOptionPane.showMessageDialog( this,
191 "Bad account number or balance", "Invalid Number Format",
192 JOptionPane.ERROR_MESSAGE );
193 }
194
195 // process exceptions from file output
196 catch ( IOException ioException ) {
197 JOptionPane.showMessageDialog( this, "Error writing to file",
198 "IO Exception", JOptionPane.ERROR_MESSAGE );
199 closeFile();
200 }
201
202 } // end if
203
204 } // end method addRecord
205
307
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (17)
308
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Writing to a sequential-access file (18)
Select location
for file here
Files and
directories are Click Save to
displayed here submit new
file name to
program
309
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reading from a sequential-access file (1)
1 // ReadSequentialFile.java
2 // This program reads a file of objects sequentially
3 // and displays each record.
4 import java.io.*;
5 import java.awt.*;
6 import java.awt.event.*;
7 import javax.swing.*;
8
9 import com.*;
10
11 public class ReadSequentialFile extends JFrame {
12 private ObjectInputStream input;
13 private BankUI userInterface;
14 private JButton nextButton, openButton;
15
16 // Constructor -- initialize the Frame
17 public ReadSequentialFile()
18 {
19 super( "Reading a Sequential File of Objects" ); Create user interface
20
21 // create instance of reusable user interface
22 userInterface = new BankUI( 4 ); // four textfields
23 getContentPane().add( userInterface, BorderLayout.CENTER );
24
310
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reading from a sequential-access file (2)
25 // get reference to generic task button doTask1 from BankUI
26 openButton = userInterface.getDoTask1Button();
27 openButton.setText( "Open File" );
Get a reference to the
28 first task button
29 // register listener to call openFile when button pressed
30 openButton.addActionListener(
31
32 // anonymous inner class to handle openButton event
33 new ActionListener() {
34
35 // close file and terminate application
36 public void actionPerformed( ActionEvent event )
37 {
38 openFile();
39 }
41 } // end anonymous inner class
42
43 ); // end call to addActionListener
44
45 // register window listener for window closing event
46 addWindowListener(
47
48 // anonymous inner class to handle windowClosing event
49 new WindowAdapter() {
311
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reading from a sequential-access file (3)
51 // close file and terminate application
52 public void windowClosing( WindowEvent event )
53 {
54 if ( input != null )
55 closeFile();
56
57 System.exit( 0 );
58 }
59
60 } // end anonymous inner class
61
62 ); // end call to addWindowListener
63
64 // get reference to generic task button doTask2 from BankUI
65 nextButton = userInterface.getDoTask2Button();
66 nextButton.setText( "Next Record" ); Get a reference to the
67 nextButton.setEnabled( false ); second task button
68
69 // register listener to call readRecord when button pressed
70 nextButton.addActionListener(
71
72 // anonymous inner class to handle nextRecord event
73 new ActionListener() {
74
312
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reading from a sequential-access file (4)
75 // call readRecord when user clicks nextRecord
76 public void actionPerformed( ActionEvent event )
77 {
78 readRecord();
79 }
80
81 } // end anonymous inner class
82
83 ); // end call to addActionListener
84
85 pack(); Instantiate a
86 setSize( 300, 200 );
JFileChooser
87 setVisible( true );
and assign it to
88
89 } // end ReadSequentialFile constructor
fileChooser
90
Method showOpenDialog
91 // enable user to select file to open
92 private void openFile()
causes the JFileChooser
93 { titled Open to appear
94 // display file dialog so user can select file to open
95 JFileChooser fileChooser = new JFileChooser();
96 fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
97
98 int result = fileChooser.showOpenDialog( this );
99 313
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reading from a sequential-access file (5)
100 // if user clicked Cancel button on dialog, return
101 if ( result == JFileChooser.CANCEL_OPTION ) Return if user clicked
102 return; Cancel button on
103 dialog
104 // obtain selected file
105 File fileName = fileChooser.getSelectedFile();
106 Retrieve selected file
107 // display error if file name invalid
108 if ( fileName == null || fileName.getName().equals( "" ) )
109 JOptionPane.showMessageDialog( this, "Invalid File Name",
110 "Invalid File Name", JOptionPane.ERROR_MESSAGE );
112 else {
114 // open file
115 try {
116 input = new ObjectInputStream(
117 new FileInputStream( fileName ) );
119 openButton.setEnabled( false ); Open selected file
120 nextButton.setEnabled( true );
121 }
122
123 // process exceptions opening file
124 catch ( IOException ioException ) {
125 JOptionPane.showMessageDialog( this, "Error Opening File",
126 "Error", JOptionPane.ERROR_MESSAGE );
127 } 314
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reading from a sequential-access file (6)
129 } // end else
130
131 } // end method openFile
132
133 // read record from file
134 public void readRecord()
135 { Method readObject
136 AccountRecord record; reads an Object from the
137 ObjectInputStream
138 // input the values from the file
139 try {
140 record = ( AccountRecord ) input.readObject();
141
142 // create array of Strings to display in GUI
143 String values[] = { String.valueOf( record.getAccount() ),
144 record.getFirstName(), record.getLastName(),
145 String.valueOf( record.getBalance() ) };
146
147 // display record contents
148 userInterface.setFieldValues( values );
149 }
150
151 // display message when end-of-file reached
152 catch ( EOFException endOfFileException ) {
153 nextButton.setEnabled( false ); 315
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reading from a sequential-access file (7)
155 JOptionPane.showMessageDialog( this, "No more records in file",
156 "End of File", JOptionPane.ERROR_MESSAGE );
157 }
159 // display error message if class is not found
160 catch ( ClassNotFoundException classNotFoundException ) {
161 JOptionPane.showMessageDialog( this, "Unable to create object",
162 "Class Not Found", JOptionPane.ERROR_MESSAGE );
163 }
165 // display error message if cannot read due to problem with file
166 catch ( IOException ioException ) {
167 JOptionPane.showMessageDialog( this,
168 "Error during read from file",
169 "Read Error", JOptionPane.ERROR_MESSAGE );
170 }
172 } // end method readRecord
173
174 // close file and terminate application
175 private void closeFile()
176 { Method closeFile
177 // close file and exit closes the current file
178 try {
179 input.close();
180 System.exit( 0 );
181 }
316
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reading from a sequential-access file (8)
183 // process exception while closing file
184 catch ( IOException ioException ) {
185 JOptionPane.showMessageDialog( this, "Error closing file",
186 "Error", JOptionPane.ERROR_MESSAGE );
187
188 System.exit( 1 );
189 }
190
191 } // end method closeFile
192
193 public static void main( String args[] )
194 {
195 new ReadSequentialFile();
196 }
197
198 } // end class ReadSequentialFile
317
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reading from a sequential-access file (9)
318
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Concurrent Programming (Multithreading)
more sequential activities (processes, tasks, threads)
can be executed concurrently
monoprocessor architectures
• interleaving, priority, preemption, time-slicing
multiprocessor architectures
distributed architectures
activities inside different threads can be
independent (asynchronous)
competing for the use of common resources (synchronized)
co operant (communicating)
319
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Thread states
Born
Thread was just created
Ready
Thread’s start method invoked
Thread can now execute; it competes with other threads for a processor to run
Running
Thread is assigned a processor and running
Dead
Thread has completed or exited
Eventually disposed of by system
Waiting
Thread has suspended its own execution until a given system state has been reached
Sleeping
Thread has suspended its own execution for a specified period of time
Blocked
Thread has been suspended by some other thread
320
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Life cycle of threads
Born
start
Ready
thread dispatch
quantum expiration (assign a processor)
yield
timeout expires
I/O completes
interrupt
interrupt
notifyAll
acquire lock
notify
Running
321
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Thread priority scheduling
Ready threads
Thread.MAX_PRIORITY Priority 10 A B
Priority 9 C
Priority 8
Priority 7 D E F
Priority 6 G
Thread.NORM_PRIORITY Priority 5 H I
Priority 4
Priority 3
Priority 2 J K
Thread.MIN_PRIORITY Priority 1
322
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Thread Class (1)
Thread () Allocates a new Thread object.
Thread (Runnable target) Allocates a new Thread object.
Thread (Runnable target, String name) Allocates a new Thread object.
Thread (String name) Allocates a new Thread object.
Thread (ThreadGroup group, Runnable target) Allocates a new Thread object.
static Thread currentThread () Returns a reference to the currently executing thread object.
String getName () Returns this thread's name.
void join () Waits for this thread to die.
void run () If this thread was constructed using a separate Runnable run
object, then that Runnable object's run method is called;
otherwise, this method does nothing and returns.
void setDaemon (boolean on) Marks this thread as either a daemon thread or a user thread.
void setPriority (int newPriority) Changes the priority of this thread.
static void sleep(long millis) Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds.
void start() Causes this thread to begin execution; the Java Virtual Machine
calls the run method of this thread.
static void yield() Causes the currently executing thread object to temporarily pause
and allow other threads to execute.
When code running in some thread creates a new Thread object, the new
thread has its priority initially set equal to the priority of the creating thread,
and is a daemon thread if and only if the creating thread is a daemon. 323
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Thread Class (2)
324
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Daemon Threads
325
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Creating and Executing Threads (1)
1 // ThreadTester.java
2 // Multiple threads printing at different intervals.
3
4 public class ThreadTester {
5
create three
6 public static void main( String [] args )
PrintThreads
7 {
8 // create and name each thread
9 PrintThread thread1 = new PrintThread( "thread1" );
10 PrintThread thread2 = new PrintThread( "thread2" );
11 PrintThread thread3 = new PrintThread( "thread3" );
12 call start methods
13 System.err.println( "Starting threads" );
14
15 thread1.start(); // start thread1 and place it in ready state
16 thread2.start(); // start thread2 and place it in ready state
17 thread3.start(); // start thread3 and place it in ready state
18
19 System.err.println( "Threads started, main ends\n" );
20
21 } // end main
22
23 } // end class ThreadTester
24
326
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Creating and Executing Threads (2)
25 // class PrintThread controls thread execution
26 class PrintThread extends Thread {
27 private int sleepTime;
PrintThread
28 extends Thread
29 // assign name to thread by calling superclass constructor
30 public PrintThread( String name )
31 {
32 super( name );
33
34 // pick random sleep time between 0 and 5 seconds
35 sleepTime = ( int ) ( Math.random() * 5001 ); Constructor initializes
36 } sleepTime
37
38 // method run is the code to be executed by new thread
39 public void run() When the thread
40 { enters the running
41 // put thread to sleep for sleepTime amount of time state, run is called
42 try {
43 System.err.println(
44 getName() + " going to sleep for " + sleepTime );
45
46 sleep( sleepTime );
47 }
48
327
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Creating and Executing Threads (3)
49 // if thread interrupted during sleep, print stack trace
50 catch ( InterruptedException exception ) {
51 exception.printStackTrace();
52 }
53
54 // print thread name
55 System.err.println( getName() + " done sleeping" );
56
57 } // end method run
58
59 } // end class PrintThread
Starting threads
Threads started, main ends
328
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Runnable Interface (1)
329
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Runnable Interface (2)
1 // RunnableTester.java
2 // Multiple threads printing at different intervals.
3
4 public class RunnableTester {
5
create three
6 public static void main( String [] args )
Threads
7 {
8 // create and name each thread
9 Thread thread1 = new Thread( new PrintThread(), "thread1" );
10 Thread thread2 = new Thread( new PrintThread(), "thread2" );
11 Thread thread3 = new Thread( new PrintThread(), "thread3" );
12 call start methods
13 System.err.println( "Starting threads" );
14
15 thread1.start(); // start thread1 and place it in ready state
16 thread2.start(); // start thread2 and place it in ready state
17 thread3.start(); // start thread3 and place it in ready state
18
19 System.err.println( "Threads started, main ends\n" );
20
21 } // end main
22
23 } // end class RunnableTester
24
330
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Runnable Interface (3)
25 // class PrintThread controls thread execution
26 class PrintThread implements Runnable {
PrintThread
27 private int sleepTime; implements
28 Runnable
29 // assign sleep time
30 public PrintThread()
31 {
32 // pick random sleep time between 0 and 5 seconds
33 sleepTime = ( int ) ( Math.random() * 5001 ); Constructor initializes
34 } sleepTime
35
36 // method run is the code to be executed by new thread
37 public void run()
When the thread
38 {
enters the running
40 Thread cT = Thread.currentThread();
41 // put thread to sleep for sleepTime amount of time
state, run is called
42 try {
43 System.err.println(
44 cT.getName() + " going to sleep for " + sleepTime );
45
46 Thread.sleep( sleepTime );
47 }
48
331
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Runnable Interface (4)
49 // if thread interrupted during sleep, print stack trace
50 catch ( InterruptedException exception ) {
51 exception.printStackTrace();
52 }
53
54 // print thread name
55 System.err.println( cT.getName() + " done sleeping" );
56
57 } // end method run
58
59 } // end class PrintThread
Starting threads
Threads started, main ends
332
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Thread Synchronization (1)
Java uses monitors (C.A.R. Hoare, 1974) for thread synchronization
Every object with synchronized methods is a monitor
The monitor allows one thread at a time to execute a
synchronized method on the object
Mutual exclusion is accomplished by locking the object when a
synchronized method is invoked
If there are several synchronized methods in an object, only
one of them may be active at once; all other threads attempting to
invoke synchronized methods must wait
When a synchronized method finishes executing, the lock on
the object is released and the monitor lets the highest-priority ready
thread attempting to invoke a synchronized method proceed
333
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Thread Synchronization (2)
334
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Producer/Consumer Relationship (1)
Buffer
Shared memory region
Producer thread
Generates data to add to buffer
Calls wait if consumer has not read previous message in
buffer
Writes to empty buffer and calls notify for consumer
Consumer thread
Reads data from buffer
Calls wait if buffer empty
Threads must be synchronized to avoid corrupted data
335
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Producer/Consumer Relationship (2)
336
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Producer/Consumer Relationship (3)
1 // SynchronizedBuffer.java
2 // SynchronizedBuffer synchronizes access to a single shared integer.
3
4 public class SynchronizedBuffer {
5 private int buffer = -1; // shared by producer and consumer threads
6 private int occupiedBufferCount = 0; // count of occupied buffers
7
8 // place value into buffer Method set is declared
9 public synchronized void set( int value ) synchronized
10 {
11 // for output purposes, get name of thread that called this method
12 String name = Thread.currentThread().getName();
14 // while there are no empty locations, place thread in waiting state
15 while ( occupiedBufferCount == 1 ) {
17 // output thread information and buffer information, then wait
18 try {
19 System.err.println( name + " tries to write." );
20 System.err.println( "Buffer full. " + name + " waits.\n" );
21 wait();
22 }
Wait while the buffer is filled
24 // if waiting thread interrupted, print stack trace
25 catch ( InterruptedException exception ) {
26 exception.printStackTrace();
27 }
28 } // end while 337
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Producer/Consumer Relationship (4)
30
31 buffer = value; // set new buffer value
32
33 // indicate producer cannot store another value Write to the buffer
34 // until consumer retrieves current buffer value
35 ++occupiedBufferCount;
Increment the buffer count
36
37 displayState( name + " writes " + buffer );
Alert a waiting thread
38
39 notify(); // tell a waiting thread to enter ready state
40
41 } // end method set; releases lock on SynchronizedBuffer
42
43 // return value from buffer Method get is declared
44 public synchronized int get() synchronized
45 {
46 // for output purposes, get name of thread that called this method
47 String name = Thread.currentThread().getName();
48
338
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Producer/Consumer Relationship (5)
49 // while no data to read, place thread in waiting state
50 while ( occupiedBufferCount == 0 ) {
51
52 // output thread information and buffer information, then wait
53 try {
54 System.err.println( name + " tries to read." );
55 System.err.println( "Buffer empty. " + name + " waits.\n" );
56 wait();
Wait while the buffer is empty
57 }
59 // if waiting thread interrupted, print stack trace
60 catch ( InterruptedException exception ) {
61 exception.printStackTrace();
62 }
63
64 } // end while
65
66 // indicate that producer can store another value
67 // because consumer just retrieved buffer value
68 --occupiedBufferCount; Decrement the buffer count
69
70 displayState( name + " reads " + buffer );
Alert a waiting thread
71
72 notify(); // tell a waiting thread to become ready to execute
73
Return the buffer
74 return buffer; 339
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Producer/Consumer Relationship (6)
75
76 } // end method get; releases lock on SynchronizedBuffer
77
78 // display current operation and buffer state
79 public void displayState( String operation )
80 {
81 StringBuffer outputLine = new StringBuffer( operation );
82
83 outputLine.append("\t\t" + buffer + "\t" + occupiedBufferCount );
84 System.err.println( outputLine );
85 System.err.println();
86 }
87
88 } // end class SynchronizedBuffer
340
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Producer/Consumer Relationship (7)
1 // Producer.java
2 // Producer's run method controls a thread that
3 // stores values from 1 to 4 in sharedLocation.
4
5 public class Producer extends Thread {
6 private SynchronizedBuffer sharedLocation; // reference to shared object
7
8 // constructor
9 public Producer(SynchronizedBuffer shared )
10 {
11 super( "Producer" );
12 sharedLocation = shared;
13 }
14
15 // store values from 1 to 4 in sharedLocation
16 public void run()
17 {
18 for ( int count = 1; count <= 4; count++ ) {
19
20 // sleep 0 to 3 seconds, then place value in Buffer
21 try {
22 Thread.sleep( ( int ) ( Math.random() * 3001 ) );
23 sharedLocation.set( count );
24 }
25 341
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Producer/Consumer Relationship (8)
342
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Producer/Consumer Relationship (9)
1 // Consumer.java
2 // Consumer's run method controls a thread that loops four
3 // times and reads a value from sharedLocation each time.
4
5 public class Consumer extends Thread {
6 private SynchronizedBuffer sharedLocation; // reference to shared object
7
8 // constructor
9 public Consumer(SynchronizedBuffer shared )
10 {
11 super( "Consumer" );
12 sharedLocation = shared;
13 }
14
15 // read sharedLocation's value four times and sum the values
16 public void run()
17 {
18 int sum = 0;
20 for ( int count = 1; count <= 4; count++ ) {
21
22 // sleep 0 to 3 seconds, read value from Buffer and add to sum
23 try {
24 Thread.sleep( ( int ) ( Math.random() * 3001 ) );
25 sum += sharedLocation.get();
26 } 343
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Producer/Consumer Relationship (10)
344
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Producer/Consumer Relationship (11)
1 // SharedBufferTest.java
2 // SharedBufferTest creates producer and consumer threads.
3
4 public class SharedBufferTest {
5
6 public static void main( String [] args )
7 {
8 // create shared object used by threads
11 SynchronizedBuffer sharedLocation = new SynchronizedBuffer();
12
13 // Display column heads for output
14 StringBuffer columnHeads = new StringBuffer( "Operation" );
16 columnHeads.append("\t\t\tBuffer\tOccupied_Count" );
17 System.err.println( columnHeads );
18 System.err.println();
19 sharedLocation.displayState( "Initial State\t" );
Create a Producer and
20
21 // create producer and consumer objects
a Consumer
22 Producer producer = new Producer( sharedLocation );
23 Consumer consumer = new Consumer( sharedLocation );
25 producer.start(); // start producer thread
26 consumer.start(); // start consumer thread
27
28 } // end main
30 } // end class SharedBufferTest 345
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Producer/Consumer Relationship (12)
346
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Message buffer (1)
347
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Message buffer (2)
348
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Message buffer (3)
1. // MessageBuffer.java
2. // MessageBuffer synchronizes access to a single shared integer.
353
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Readers and Writers (2)
1. // AccessPolicy.java
2. // AccessPolicy synchronizes access to shared data.
3. import java.util.*;
355
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Readers and Writers (4)
15. public synchronized void readRequest()
16. {
17. // for output purposes, get name of thread that called this method
18. String name = Thread.currentThread().getName();
19. // while there are running or waiting writers, place thread in waiting state
20. while ( writing || !waitingWriters.isEmpty() ) {
21. // output thread information and buffer information, then wait
22. try {
23. System.err.println( name + " tries to read. Access denied: writing="
+ writing + " runningReaders=" + runningReaders + " waitingWriters="
+ waitingWriters + ".\n" );
24. wait();
25. }
26. // if waiting thread interrupted, print stack trace
27. catch ( InterruptedException exception ) {
28. exception.printStackTrace();
29. }
30. } // end while
31. runningReaders ++ ;
32. notify(); // tell waiting readers to enter ready state
33. } // end method readRequest
356
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Readers and Writers (5)
34. public synchronized void writeRequest()
35. {
36. // for output purposes, get name of thread that called this method
37. String name = Thread.currentThread().getName();
38. // while there are running readers or writers, place thread in waiting state
39. while ( writing || runningReaders != 0 ) {
40. // output thread information, then wait
41. try {
42. waitingWriters.add(name) ;
43. System.err.println( name + " tries to write. Access denied: writing="
+ writing + " runningReaders=" + runningReaders + " waitingWriters="
+ waitingWriters + ".\n" );
44. wait();
45. }
46. // if waiting thread interrupted, print stack trace
47. catch ( InterruptedException exception ) {
48. exception.printStackTrace();
49. }
50. } // end while
51. writing = true;
52. waitingWriters.remove(name) ;
53. } // end method writeRequest
357
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Readers and Writers (6)
59.
60. public synchronized void writeRelease()
61. {
62. writing = false;
63. notifyAll(); // tell waiting threads to enter ready state
64. } // end method writeRelease
65. } // end class AccessPolicy
358
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Readers and Writers (7)
1. public class SharedData {
2. private Object data ; // shared by readers and writers threads
3. private AccessPolicy access;
4. public SharedData()
5. {
6. access = new AccessPolicy();
7. }
8. public Object read()
9. {
10. access.readRequest();
11. System.err.println( Thread.currentThread().getName() + " starts reading.\n" );
12. for (int i=1 ;i <= 1000; i++) System.out.print("") ; // reading time
13. Object d = data;
14. System.err.println( Thread.currentThread().getName() + " read " + d + ".\n" );
15. access.readRelease();
16. return d;
17. }
18. public void write(Object d)
19. {
20. access.writeRequest();
21. System.err.println( Thread.currentThread().getName() + " starts writing.\n" );
22. for (int i=1 ;i <= 1000; i++) System.out.print(""); // writing time
23. data = d;
24. System.err.println( Thread.currentThread().getName() + " wrote " + d + ".\n" );
25. access.writeRelease();
26. }
27. } // end class SharedData
359
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Readers and Writers (7)
1. // Writer.java
2. // Writer's run method controls a thread that writes a value into sharedData.
362
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Readers and Writers (10)
******************************************************
Reader-r1 starts reading.
Writer-w1 tries to write. Access denied: writing=false runningReaders=1
waitingWriters=[Writer-w1].
Reader-r2 tries to read. Access denied: writing=false runningReaders=1
waitingWriters=[Writer-w1].
Writer-w2 tries to write. Access denied: writing=false runningReaders=1
waitingWriters=[Writer-w1, Writer-w2].
Reader-r1 read null.
Writer-w1 starts writing.
Writer-w1 wrote Writer-w1.
Reader-r2 tries to read. Access denied: writing=false runningReaders=0
waitingWriters=[Writer-w2].
Writer-w2 starts writing.
Writer-w2 wrote Writer-w2.
Reader-r2 starts reading.
Reader-r2 read Writer-w2.
363
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Graphical User Interface (GUI)
Object
java.lang.Object
java.awt.Component
Component
Container
java.awt.Container
java.awt.Panel
Container
java.awt.Window
Container
JComponent
javax.swing.JComponent
Container Container
java.applet.Applet java.awt.Frame
javax.swing.JApplet
Container
javax.swing.JFrame
Container
365
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: GUI Class Relationships
366
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: GUI Containers
Top-Level Containers
Applet
Frame
Dialog
General-Purpose Containers
Containment hierarchy
a tree of components that has a top-level container
as its root
Each top-level container has a content pane
a Container object that contains the visible
components in that top-level container's GUI
the content pane of a top-level container is found by
calling the getContentPane() method
368
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JComponent subclasses
JComponent Description
JLabel An area where uneditable text or icons can be displayed.
JTextField An area in which the user inputs data from the keyboard. The area can also
display information.
JButton An area that triggers an event when clicked with the mouse.
JComboBox A drop- down list of items from which the user can make a selection by
clicking an item in the list or possibly by typing into the box.
JList An area containing a list of items from which the user can make a selection
by clicking on any element in the list. Multiple elements can be selected.
369
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JLabel (1)
Tool tip
370
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JLabel (2)
1 // LabelTest.java
2 // Demonstrating the JLabel class.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public class LabelTest extends JFrame {
8 private JLabel label1, label2, label3;
9
10 // set up GUI
11 public LabelTest()
12 {
13 super( "Testing JLabel" );
14
15 // get content pane and set its layout
16 Container container = getContentPane();
17 container.setLayout( new FlowLayout() );
18
19 // JLabel constructor with a string argument
20 label1 = new JLabel( "Label with text" );
21 label1.setToolTipText( "This is label1" );
Tool tip is text that appears when
22 container.add( label1 );
23
user moves cursor over JLabel
24 // JLabel constructor with string, Icon and alignment arguments
25 Icon bug = new ImageIcon( "bug1.gif" ); 371
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JLabel (3)
26 label2 = new JLabel( "Label with text and icon", bug,
27 SwingConstants.LEFT );
28 label2.setToolTipText( "This is label2" );
29 container.add( label2 );
30
31 // JLabel constructor no arguments
32 label3 = new JLabel();
33 label3.setText( "Label with icon and text at bottom" );
34 label3.setIcon( bug );
35 label3.setHorizontalTextPosition( SwingConstants.CENTER );
36 label3.setVerticalTextPosition( SwingConstants.BOTTOM );
37 label3.setToolTipText( "This is label3" );
38 container.add( label3 );
39
40 setSize( 275, 170 );
41 setVisible( true );
42
43 } // end constructor
44
45 public static void main( String args[] )
46 {
47 LabelTest application = new LabelTest();
48 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
49 }
50 } // end class LabelTest 372
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JLabel (4)
373
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: Model/View/Controller (1)
374
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: Model/View/Controller (2)
Model
data structure, no visual representation
Views
visual representations
Controllers
user interaction
376
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: Observer Pattern (1)
Context
An object, called the subject, is source of events
One or more observer objects want to be notified when such
an event occurs
Solution
Define an observer interface type. All concrete observers
implement it
The subject maintains a collection of observers.
The subject supplies methods for attaching and detaching
observers
Whenever an event occurs, the subject notifies all observers
377
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: Observer Pattern (2)
378
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: An Observer Pattern Example
Observer ActionListener
attach() addActionListener()
notify() actionPerformed()
379
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Event-handling model
380
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Event classes
Object
java.lang.Object
ActionEvent
ActionEvent
java.util.EventObject
EventObject
AdjustmentEvent
AdjustmentEvent
java.awt.AWTEvent
AWTEvent ContainerEvent
ContainerEvent
ItemEvent
ItemEvent
FocusEvent
FocusEvent
TextEvent
TextEvent
PaintEvent
PaintEvent
ComponentEvent
ComponentEvent
WindowEvent
WindowEvent
InputEvent
InputEvent
KeyEvent MouseEvent
KeyEvent MouseEvent
MouseWheelEvent
MouseWheelEvent
381
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Event-listener interfaces
interface
«interface»
ActionListener
ActionListener
interface
«interface»
AdjustmentListener
AdjustmentListener
«interface»
interface
ComponentListener
ComponentListener
interface
«interface»
ContainerListener
ContainerListener
interface
«interface»
FocusListener
FocusListener
«interface»
interface «interface»
interface
EventListener
java.util.EventListener ItemListener
«interface»
interface
KeyListener
KeyListener
interface
«interface»
MouseListener
MouseListener
interface
«interface»
MouseMotionListener
MouseMotionListener
interface
«interface»
TextListener
TextListener
«interface»
interface
WindowListener
WindowListener
382
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Text Components
383
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Text Field (1)
JTextField
Single-line area in which user can enter text
JPasswordField
Extends JTextField
Hides characters that user enters
384
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JTextField (2)
1 // TextFieldTest.java
2 // Demonstrating the JTextField class.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public class TextFieldTest extends JFrame {
8 private JTextField textField1, textField2, textField3;
9 private JPasswordField passwordField;
10
11 // set up GUI
12 public TextFieldTest()
13 {
14 super( "Testing JTextField and JPasswordField" );
15
16 Container container = getContentPane();
17 container.setLayout( new FlowLayout() );
18
19 // construct textfield with default sizing
20 textField1 = new JTextField( 10 );
21 container.add( textField1 );
22
23 // construct textfield with default text
24 textField2 = new JTextField( "Enter text here" );
25 container.add( textField2 ); 385
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JTextField (3)
28 // construct textfield with default text,
29 // 20 visible elements and no event handler
29 textField3 = new JTextField( "Uneditable text field", 20 );
30 textField3.setEditable( false );
31 container.add( textField3 );
32
33 // construct passwordfield with default text
34 passwordField = new JPasswordField( "Hidden text" );
35 container.add( passwordField );
36
37 // register event handlers
38 TextFieldHandler handler = new TextFieldHandler();
39 textField1.addActionListener( handler );
40 textField2.addActionListener( handler );
41 textField3.addActionListener( handler ); Register GUI components with
42 passwordField.addActionListener( handler ); TextFieldHandler (subtype
44 setSize( 325, 100 ); of ActionListener)
45 setVisible( true );
47 } // end constructor TextFieldTest
48
49 public static void main( String args[] )
50 {
51 TextFieldTest application = new TextFieldTest();
52 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
53 } 386
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JTextField (4)
55 // private inner class for event handling
56 private class TextFieldHandler implements ActionListener {
57
58 // process textfield events
59 public void actionPerformed( ActionEvent event )
60 {
61 String string = ""; Method actionPerformed
62 invoked when user presses
63 // user pressed Enter in JTextField textField1 Enter in GUI field
64 if ( event.getSource() == textField1 )
65 string = "textField1: " + event.getActionCommand();
66
67 // user pressed Enter in JTextField textField2
68 else if ( event.getSource() == textField2 )
69 string = "textField2: " + event.getActionCommand();
70
71 // user pressed Enter in JTextField textField3
72 else if ( event.getSource() == textField3 )
73 string = "textField3: " + event.getActionCommand();
74
75 // user pressed Enter in JTextField passwordField
76 else if ( event.getSource() == passwordField ) {
77 string = "passwordField: " +
78 new String( passwordField.getPassword() );
79 } 387
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JTextField (5)
81 JOptionPane.showMessageDialog( null, string );
82
83 } // end method actionPerformed
84
85 } // end private inner class TextFieldHandler
86
87 } // end class TextFieldTest
388
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Event registration for JTextField
How did event handler get registered?
Through component’s method addActionListener
Lines 39-42 of TextFieldTest.java
How does component know to call actionPerformed?
Event is dispatched only to listeners of appropriate type
Each event type has corresponding event-listener interface
• Event ID specifies event type that occurred
textField1 handler
...
JComponent
JComponent
AbstractButton
AbstractButton
JButton JToggleButton
JButton JToggleButton
JCheckBox JRadioButton
JCheckBox JRadioButton
390
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JButton (1)
1 // ButtonTest.java
2 // Creating JButtons.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public class ButtonTest extends JFrame {
8 private JButton plainButton, fancyButton;
9
10 // set up GUI
11 public ButtonTest()
12 {
13 super( "Testing Buttons" );
14
15 // get content pane and set its layout
16 Container container = getContentPane();
17 container.setLayout( new FlowLayout() );
19 // create buttons
20 plainButton = new JButton( "Plain Button" );
21 container.add( plainButton );
23 Icon bug1 = new ImageIcon( "bug1.gif" );
24 Icon bug2 = new ImageIcon( "bug2.gif" );
25 fancyButton = new JButton( "Fancy Button", bug1 );
26 fancyButton.setRolloverIcon( bug2 );
27 container.add( fancyButton ); 391
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JButton (2)
28
29 // create an instance of inner class ButtonHandler
30 // to use for button event handling
31 ButtonHandler handler = new ButtonHandler();
32 fancyButton.addActionListener( handler );
33 plainButton.addActionListener( handler );
35 setSize( 275, 100 );
36 setVisible( true );
38 } // end ButtonTest constructor
39
40 public static void main( String args[] )
41 {
42 ButtonTest application = new ButtonTest();
43 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
44 }
45
392
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JButton (3)
46 // inner class for button event handling
47 private class ButtonHandler implements ActionListener {
48
49 // handle button event
When user clicks JButton,
50 public void actionPerformed( ActionEvent event ) ButtonHandler invokes
51 { method actionPerformed
52 JOptionPane.showMessageDialog( ButtonTest.this, of all registered listeners
53 "You pressed: " + event.getActionCommand() );
54 }
55
56 } // end private inner class ButtonHandler
57
58 } // end class ButtonTest
393
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JCheckBox (1)
1 // CheckBoxTest.java
2 // Creating JCheckBox buttons.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public class CheckBoxTest extends JFrame {
8 private JTextField field;
9 private JCheckBox bold, italic;
10
11 // set up GUI
12 public CheckBoxTest()
13 {
14 super( "JCheckBox Test" );
15
16 // get content pane and set its layout
17 Container container = getContentPane();
18 container.setLayout( new FlowLayout() );
19
20 // set up JTextField and set its font
21 field = new JTextField( "Watch the font style change", 20 );
22 field.setFont( new Font( "Serif", Font.PLAIN, 14 ) );
23 container.add( field );
24
394
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JCheckBox (2)
25 // create checkbox objects
26 bold = new JCheckBox( "Bold" );
27 container.add( bold );
28
29 italic = new JCheckBox( "Italic" );
30 container.add( italic );
31
32 // register listeners for JCheckBoxes
33 CheckBoxHandler handler = new CheckBoxHandler();
34 bold.addItemListener( handler );
35 italic.addItemListener( handler );
36
37 setSize( 275, 100 );
38 setVisible( true );
39
40 } // end CheckBoxText constructor
41
42 public static void main( String args[] )
43 {
44 CheckBoxTest application = new CheckBoxTest();
45 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
46 }
47
395
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JCheckBox (3)
48 // private inner class for ItemListener event handling
49 private class CheckBoxHandler implements ItemListener {
50 private int valBold = Font.PLAIN;
51 private int valItalic = Font.PLAIN; When user selects JCheckBox,
52 CheckBoxHandler invokes
53 // respond to checkbox events method itemStateChanged of
54 public void itemStateChanged( ItemEvent event ) all registered listeners
55 {
56 // process bold checkbox events
57 if ( event.getSource() == bold )
58 valBold = bold.isSelected() ? Font.BOLD : Font.PLAIN;
59
60 // process italic checkbox events
61 if ( event.getSource() == italic )
62 valItalic = italic.isSelected() ? Font.ITALIC : Font.PLAIN;
63
64 // set text field font
65 field.setFont( new Font( "Serif", valBold + valItalic, 14 ) );
66
67 } // end method itemStateChanged
Change JTextField font, depending
68 on which JCheckBox was selected
69 } // end private inner class CheckBoxHandler
70
71 } // end class CheckBoxTest
396
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JCheckBox (4)
397
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JRadioButton (1)
1 // RadioButtonTest.java
2 // Creating radio buttons using ButtonGroup and JRadioButton.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public class RadioButtonTest extends JFrame {
8 private JTextField field;
9 private Font plainFont, boldFont, italicFont, boldItalicFont;
10 private JRadioButton plainButton, boldButton, italicButton, boldItalicButton;
12 private ButtonGroup radioGroup;
13
14 // create GUI and fonts
15 public RadioButtonTest()
16 {
17 super( "RadioButton Test" );
18
19 // get content pane and set its layout
20 Container container = getContentPane();
21 container.setLayout( new FlowLayout() );
22
23 // set up JTextField
24 field = new JTextField( "Watch the font style change", 25 );
25 container.add( field );
26 398
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JRadioButton (2)
27 // create radio buttons
28 plainButton = new JRadioButton( "Plain", true );
29 container.add( plainButton );
31 boldButton = new JRadioButton( "Bold", false );
32 container.add( boldButton );
34 italicButton = new JRadioButton( "Italic", false );
35 container.add( italicButton );
37 boldItalicButton = new JRadioButton( "Bold/Italic", false );
38 container.add( boldItalicButton );
39
40 // create logical relationship between JRadioButtons
41 radioGroup = new ButtonGroup();
42 radioGroup.add( plainButton );
JRadioButtons belong
43 radioGroup.add( boldButton );
to ButtonGroup
44 radioGroup.add( italicButton );
45 radioGroup.add( boldItalicButton );
46
47 // create font objects
48 plainFont = new Font( "Serif", Font.PLAIN, 14 );
49 boldFont = new Font( "Serif", Font.BOLD, 14 );
50 italicFont = new Font( "Serif", Font.ITALIC, 14 );
51 boldItalicFont = new Font( "Serif", Font.BOLD + Font.ITALIC, 14 );
52 field.setFont( plainFont ); // set initial font
53
399
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JRadioButton (3)
54 // register events for JRadioButtons
55 plainButton.addItemListener( new RadioButtonHandler( plainFont ) );
56 boldButton.addItemListener( new RadioButtonHandler( boldFont ) );
57 italicButton.addItemListener( new RadioButtonHandler( italicFont ) );
59 boldItalicButton.addItemListener( new RadioButtonHandler( boldItalicFont ) );
62 setSize( 300, 100 );
63 setVisible( true );
64
65 } // end RadioButtonTest constructor
66
67 public static void main( String args[] )
68 {
69 RadioButtonTest application = new RadioButtonTest();
70 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
71 }
72
73 // private inner class to handle radio button events
74 private class RadioButtonHandler implements ItemListener {
75 private Font font;
76
77 public RadioButtonHandler( Font f )
78 {
79 font = f;
80 }
400
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JRadioButton (4)
82 // handle radio button events
83 public void itemStateChanged( ItemEvent event )
84 {
85 field.setFont( font );
When user selects JRadioButton,
86 } RadioButtonHandler invokes
87 method itemStateChanged of
88 } // end private inner class RadioButtonHandler all registered listeners
89
90 } // end class RadioButtonTest
401
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: ComboBox (1)
JComboBox
List of items from which user can select
Also called a drop-down list
402
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JComboBox (2)
1 // ComboBoxTest.java
2 // Using a JComboBox to select an image to display.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public class ComboBoxTest extends JFrame {
8 private JComboBox imagesComboBox;
9 private JLabel label;
10
11 private String names[] = {"bug1.gif","bug2.gif","travelbug.gif","buganim.gif"};
13 private Icon icons[] = { new ImageIcon( names[ 0 ] ),
14 new ImageIcon( names[ 1 ] ), new ImageIcon( names[ 2 ] ),
15 new ImageIcon( names[ 3 ] ) };
16
17 // set up GUI
18 public ComboBoxTest()
19 {
20 super( "Testing JComboBox" );
21
22 // get content pane and set its layout
23 Container container = getContentPane();
24 container.setLayout( new FlowLayout() );
403
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JComboBox (3)
26 // set up JComboBox and register its event handler
27 imagesComboBox = new JComboBox( names );
28 imagesComboBox.setMaximumRowCount( 3 );
29 imagesComboBox.addItemListener(
30
31 new ItemListener() { // anonymous inner class
32
33 // handle JComboBox event
34 public void itemStateChanged( ItemEvent event )
35 {
36 // determine whether check box selected
37 if ( event.getStateChange() == ItemEvent.SELECTED )
38 label.setIcon( icons[ imagesComboBox.getSelectedIndex() ] );
40 }
41
When user selects item in JComboBox,
42 } // end anonymous inner class
43
ItemListener invokes method
44 ); // end call to addItemListener itemStateChanged of all registered listeners
45
46 container.add( imagesComboBox );
47
48 // set up JLabel to display ImageIcons
49 label = new JLabel( icons[ 0 ] );
50 container.add( label );
404
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JComboBox (4)
52 setSize( 350, 100 );
53 setVisible( true );
54
55 } // end ComboBoxTest constructor
56
57 public static void main( String args[] )
58 {
59 ComboBoxTest application = new ComboBoxTest();
60 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
61 }
62
63 } // end class ComboBoxTest
405
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JList
Series of items
Single-selection
• user can select one item
Multiple-selection
• select many items
• allows continuous range selection
406
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JList – single selection (1)
1 // ListTest.java
2 // Selecting colors from a JList.
3 import java.awt.*;
4 import javax.swing.*;
5 import javax.swing.event.*;
6
7 public class ListTest extends JFrame {
8 private JList colorList;
9 private Container container;
10
11 private final String colorNames[] = { "Black", "Blue", "Cyan",
12 "Dark Gray", "Gray", "Green", "Light Gray", "Magenta",
13 "Orange", "Pink", "Red", "White", "Yellow" };
14
15 private final Color colors[] = { Color.black, Color.blue, Color.cyan,
16 Color.darkGray, Color.gray, Color.green, Color.lightGray,
17 Color.magenta, Color.orange, Color.pink, Color.red, Color.white,
18 Color.yellow };
19
20 // set up GUI
21 public ListTest()
22 {
23 super( "List Test" );
24
407
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JList – single selection (2)
25 // get content pane and set its layout
26 container = getContentPane();
27 container.setLayout( new FlowLayout() );
28
29 // create a list with items in colorNames array
30 colorList = new JList( colorNames );
31 colorList.setVisibleRowCount( 5 );
32
33 // do not allow multiple selections
34 colorList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
35
36 // add a JScrollPane containing JList to content pane
37 container.add( new JScrollPane( colorList ) );
38 colorList.addListSelectionListener(
40 new ListSelectionListener() { // anonymous inner class
42 // handle list selection events
43 public void valueChanged( ListSelectionEvent event )
44 {
45 container.setBackground(
46 colors[ colorList.getSelectedIndex() ] );
47 }
49 } // end anonymous inner class
When user selects item in JList,
ListSelectionListener invokes
50
method valueChanged of all registered
51 ); // end call to addListSelectionListener
listeners
408
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JList – single selection (3)
52
53 setSize( 350, 150 );
54 setVisible( true );
55
56 } // end ListTest constructor
57
58 public static void main( String args[] )
59 {
60 ListTest application = new ListTest();
61 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
62 }
63
64 } // end class ListTest
409
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JList – multiple selection (1)
1 // MultipleSelectionTest.java
2 // Copying items from one List to another.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public class MultipleSelectionTest extends JFrame {
8 private JList colorList, copyList;
9 private JButton copyButton;
10 private final String colorNames[] = { "Black", "Blue", "Cyan",
11 "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange",
12 "Pink", "Red", "White", "Yellow" };
13
14 // set up GUI
15 public MultipleSelectionTest()
16 {
17 super( "Multiple Selection Lists" );
18
19 // get content pane and set its layout
20 Container container = getContentPane();
21 container.setLayout( new FlowLayout() );
22
410
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JList – multiple selection (2)
23 // set up JList colorList
24 colorList = new JList( colorNames );
25 colorList.setVisibleRowCount( 5 );
26 colorList.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
28 container.add( new JScrollPane( colorList ) );
29
30 // create copy button and register its listener
31 copyButton = new JButton( "Copy >>>" );
32 copyButton.addActionListener(
33
34 new ActionListener() { // anonymous inner class
35
36 // handle button event
37 public void actionPerformed( ActionEvent event )
38 {
39 // place selected values in copyList
40 copyList.setListData( colorList.getSelectedValues() );
41 }
42
When user presses JButton, JList
43 } // end anonymous inner class
copyList adds items that user
44
45 ); // end call to addActionListener
selected from JList colorList
46
47 container.add( copyButton );
411
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JList – multiple selection (3)
49 // set up JList copyList
50 copyList = new JList( );
51 copyList.setVisibleRowCount( 5 );
52 copyList.setFixedCellWidth( 100 );
53 copyList.setFixedCellHeight( 15 );
54 copyList.setSelectionMode( ListSelectionModel.SINGLE_INTERVAL_SELECTION );
56 container.add( new JScrollPane( copyList ) );
57
58 setSize( 300, 130 );
59 setVisible( true );
61 } // end constructor MultipleSelectionTest
62
63 public static void main( String args[] )
64 {
65 MultipleSelectionTest application = new MultipleSelectionTest();
66 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
67 }
68
69 } // end class MultipleSelectionTest
412
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Mouse Event Handling (1)
MouseListener and MouseMotionListener interface methods
Methods of interface MouseListener
417
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: Strategy Pattern (1)
Context
A class can benefit from different variants for an algorithm
Clients sometimes want to replace standard algorithms with
custom versions
Solution
Define an interface type that is an abstraction for the
algorithm
Actual strategy classes realize this interface type.
Clients can supply strategy objects
Whenever the algorithm needs to be executed, the context
class calls the appropriate methods of the strategy object
418
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: Strategy Pattern (2)
419
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
OOA/D: A Strategy Pattern Example
420
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Layout managers (1)
Provided for arranging GUI components
Provide basic layout capabilities
Processes layout details
Programmer can concentrate on basic “look and feel”
Interface LayoutManager
Layout manager Description
FlowLayout Default for java.awt.Applet, java.awt.Panel and
javax.swing.JPanel . Places components sequentially (left to right)
in the order they were added. It is also possible to specify the order of
the components by using the Container method add, which takes a
Component and an integer index position as arguments.
BorderLayout D efault for the content panes of JFrame s (and other windows) and
JApplets. Arranges the components into five areas: NORTH , SOUTH,
EAST, WEST and CENTER.
422
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: GridLayout (1)
1 // GridLayoutDemo.java Demonstrating GridLayout.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public class GridLayoutDemo extends JFrame implements ActionListener {
8 private JButton buttons[];
9 private final String names[] =
10 { "one", "two", "three", "four", "five", "six" };
11 private boolean toggle = true;
12 private Container container;
13 private GridLayout grid1, grid2;
14
15 // set up GUI
16 public GridLayoutDemo()
17 {
18 super( "GridLayout Demo" ); Create GridLayout grid1
19 with 2 rows and 3 columns
20 // set up layouts hgap = 5 vgap = 5
21 grid1 = new GridLayout( 2, 3, 5, 5 );
22 grid2 = new GridLayout( 3, 2 ); Create GridLayout grid2
23 with 3 rows and 2 columns
24 // get content pane and set its layout
25 container = getContentPane();
26 container.setLayout( grid1 ); 423
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: GridLayout (2)
28 // create and add buttons
29 buttons = new JButton[ names.length ];
30
31 for ( int count = 0; count < names.length; count++ ) {
32 buttons[ count ] = new JButton( names[ count ] );
33 buttons[ count ].addActionListener( this );
34 container.add( buttons[ count ] );
35 }
36
37 setSize( 300, 150 );
38 setVisible( true );
39
40 } // end constructor GridLayoutDemo
41
42 // handle button events by toggling between layouts
43 public void actionPerformed( ActionEvent event )
44 {
45 if ( toggle ) Toggle current
46 container.setLayout( grid2 ); GridLayout when
47 else user presses JButton
48 container.setLayout( grid1 );
49
50 toggle = !toggle; // set toggle to opposite value
51 container.validate();
52 } 424
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: GridLayout (3)
53
54 public static void main( String args[] )
55 {
56 GridLayoutDemo application = new GridLayoutDemo();
57 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
58 }
59
60 } // end class GridLayoutDemo
425
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JPanel (1)
Panel
Helps organize components
Class JPanel is JComponent subclass
May have components (and other panels) added to
them
By default, panels don't paint anything except for
their background
426
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JPanel (2)
1 // PanelDemo.java
2 // Using a JPanel to help lay out components.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public class PanelDemo extends JFrame {
8 private JPanel buttonPanel;
9 private JButton buttons[];
10
11 // set up GUI
12 public PanelDemo()
13 {
14 super( "Panel Demo" );
15
16 // get content pane
17 Container container = getContentPane();
18
19 // create buttons array
20 buttons = new JButton[ 5 ];
21
22 // set up panel and set its layout
Create JPanel to hold JButtons
23 buttonPanel = new JPanel();
24 buttonPanel.setLayout( new GridLayout( 1, buttons.length ) );
427
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JPanel (3)
26 // create and add buttons
27 for ( int count = 0; count < buttons.length; count++ ) {
28 buttons[ count ] = new JButton( "Button " + ( count + 1 ) );
29 buttonPanel.add( buttons[ count ] );
30 } Add JButtons to JPanel
31
32 container.add( buttonPanel, BorderLayout.SOUTH );
33
34 setSize( 425, 150 );
35 setVisible( true ); Add JPanel to SOUTH
36 region of Container
37 } // end constructor PanelDemo
38
39 public static void main( String args[] )
40 {
41 PanelDemo application = new PanelDemo();
42 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
43 }
44
45 } // end class PanelDemo
428
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JTextArea (1)
JTextArea
can display and edit multiple lines of text
all of the text is in the same font
429
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JTextArea (2)
1 // TextAreaDemo.java
2 // Copying selected text from one textarea to another.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public class TextAreaDemo extends JFrame {
8 private JTextArea textArea1, textArea2;
9 private JButton copyButton;
10
11 // set up GUI
12 public TextAreaDemo() Create Box container for
13 { organizing GUI components
14 super( "TextArea Demo" );
15
16 Box box = Box.createHorizontalBox();
17
18 String string = "This is a demo string to\n" +
19 "illustrate copying text\nfrom one textarea to \n" +
20 "another textarea using an\nexternal event\n";
21
22 // set up textArea1
23 textArea1 = new JTextArea( string, 10, 15 ); Populate JTextArea with
24 box.add( new JScrollPane( textArea1 ) ); String, then add to Box
430
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JTextArea (3)
26 // set up copyButton
27 copyButton = new JButton( "Copy >>>" );
28 box.add( copyButton );
29 copyButton.addActionListener(
30
31 new ActionListener() { // anonymous inner class
32
33 // set text in textArea2 to selected text from textArea1
34 public void actionPerformed( ActionEvent event )
35 {
36 textArea2.setText( textArea1.getSelectedText() );
37 }
38 When user presses JButton,
39 } // end anonymous inner class textArea1’s highlighted text
40 is copied into textArea2
41 ); // end call to addActionListener
42
43 // set up textArea2
44 textArea2 = new JTextArea( 10, 15 );
45 textArea2.setEditable( false );
46 box.add( new JScrollPane( textArea2 ) );
47
48 // add box to content pane
49 Container container = getContentPane();
50 container.add( box ); // place in BorderLayout.CENTER 431
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JTextArea (4)
52 setSize( 425, 200 );
53 setVisible( true );
54
55 } // end constructor TextAreaDemo
56
57 public static void main( String args[] )
58 {
59 TextAreaDemo application = new TextAreaDemo();
60 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
61 }
62
63 } // end class TextAreaDemo
432
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Applets
435
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Overriding Applet Methods
public void init() { . . . }
To initialize the applet each time it is loaded (or reloaded)
public void start() { . . . }
To start the applet's execution, such as when the applet is loaded or when
the user revisits a page that contains the applet
public void stop() { . . . }
To stop the applet's execution, such as when the user leaves the applet's
page or quits the browser
public void destroy() { . . . }
To perform a final cleanup in preparation for unloading
public void paint(Graphics g) { . . . }
To display the applet on the screen
Method update(g) is conveniently used to call paint(g)
436
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JApplet (1)
437
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JApplet (2)
1 // WelcomeLines.java
2 // Displaying text and lines
3
4 // Java packages
5 import java.awt.Graphics; // import class Graphics
6 import javax.swing.JApplet; // import class JApplet
7
8 public class WelcomeLines extends JApplet {
9
10 // draw lines and a string on applet’s background
11 public void paint( Graphics g )
12 {
13 // call superclass version of method paint
14 super.paint( g );
15
16 // draw horizontal line from (15, 10) to (210, 10)
17 g.drawLine( 15, 10, 210, 10 );
18
19 // draw horizontal line from (15, 30) to (210, 30)
20 g.drawLine( 15, 30, 210, 30 );
21
22 // draw String between lines at location (25, 25)
23 g.drawString( "Welcome to Java Programming!", 25, 25 );
25 } // end method paint
27 } // end class WelcomeLines 438
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JApplet (3)
1 <html>
2 <applet code = "WelcomeLines.class" width = "300" height = "40">
3 </applet>
4 </html>
439
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JApplet (4)
1 // LoadImage.java
2 // Load an image and display it as an ImageIcon.
3 import java.applet.Applet;
4 import java.awt.*;
5 import javax.swing.*;
6
7 public class LoadImage extends JApplet {
8 private ImageIcon logo;
9
10 // load image when applet is loaded
11 public void init()
12 {
13 logo = new ImageIcon( "logo.gif" );
14 }
15
16 // display image
17 public void paint( Graphics g )
18 {
19 // draw icon using its paintIcon method
20 logo.paintIcon( this, g, 180, 0 );
21 }
22
23 } // end class LoadImage
440
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JApplet (5)
1 // ImageMap.java
2 // Demonstrating an image map.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public class ImageMap extends JApplet {
8 private ImageIcon mapImage;
10 private static final String captions[] = { "Common Programming Error",
11 "Good Programming Practice", "Graphical User Interface Tip",
12 "Performance Tip", "Portability Tip",
13 "Software Engineering Observation", "Error-Prevention Tip" };
14
15 // set up mouse listeners
16 public void init()
17 {
18 addMouseListener(
20 new MouseAdapter() { // anonymous inner class
22 // indicate when mouse pointer exits applet area
23 public void mouseExited( MouseEvent event )
24 {
25 showStatus( "Pointer outside applet" );
26 }
28 } // end anonymous inner class
30 ); // end call to addMouseListener 441
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JApplet (6)
32 addMouseMotionListener(
33
34 new MouseMotionAdapter() { // anonymous inner class
35
36 // determine icon over which mouse appears
37 public void mouseMoved( MouseEvent event )
38 {
39 showStatus( translateLocation(
40 event.getX(), event.getY() ) );
41 }
42
43 } // end anonymous inner class
44
45 ); // end call to addMouseMotionListener
46
47 mapImage = new ImageIcon( "icons.png" ); // get image
48
49 } // end method init
50
51 // display mapImage
52 public void paint( Graphics g )
53 {
54 super.paint( g );
55 mapImage.paintIcon( this, g, 0, 0 );
56 } 442
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JApplet (7)
58 // return tip caption based on mouse coordinates
59 public String translateLocation( int x, int y )
60 {
61 // if coordinates outside image, return immediately
62 if ( x >= mapImage.getIconWidth() || y >= mapImage.getIconHeight() )
63 return "";
64
65 // determine icon number (0 - 6)
66 int iconWidth = mapImage.getIconWidth() / 7;
67 int iconNumber = x / iconWidth;
68
69 return captions[ iconNumber ]; // return appropriate icon caption
70 }
71
72 } // end class ImageMap
443
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JApplet (8)
444
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JApplet (9)
1 // LoadAudioAndPlay.java
2 // Load an audio clip and play it.
3
4 import java.applet.*;
5 import java.awt.*;
6 import java.awt.event.*;
7 import javax.swing.*;
8
9 public class LoadAudioAndPlay extends JApplet {
10 private AudioClip sound1, sound2, currentSound;
11 private JButton playSound, loopSound, stopSound;
12 private JComboBox chooseSound;
13
14 // load the image when the applet begins executing
15 public void init()
16 {
17 Container container = getContentPane();
18 container.setLayout( new FlowLayout() );
19
20 String choices[] = { "Welcome", "Hi" };
21 chooseSound = new JComboBox( choices );
22
23 chooseSound.addItemListener(
24
25 new ItemListener() { // anonymous inner class 445
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JApplet (10)
27 // stop sound and change to sound to user's selection
28 public void itemStateChanged( ItemEvent e )
29 {
30 currentSound.stop();
31
32 currentSound =
33 chooseSound.getSelectedIndex() == 0 ? sound1 : sound2;
34 }
35
36 } // end anonymous inner class
37
38 ); // end addItemListener method call
39
40 container.add( chooseSound );
41
42 // set up button event handler and buttons
43 ButtonHandler handler = new ButtonHandler();
44
45 playSound = new JButton( "Play" );
46 playSound.addActionListener( handler );
47 container.add( playSound );
48
49 loopSound = new JButton( "Loop" );
50 loopSound.addActionListener( handler );
51 container.add( loopSound ); 446
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JApplet (11)
52
53 stopSound = new JButton( "Stop" );
54 stopSound.addActionListener( handler );
55 container.add( stopSound );
56
57 // load sounds and set currentSound
58 sound1 = getAudioClip( getDocumentBase(), "welcome.wav" );
59 sound2 = getAudioClip( getDocumentBase(), "hi.au" );
60 currentSound = sound1;
61
62 } // end method init
63
64 // stop the sound when the user switches Web pages
65 public void stop()
66 {
67 currentSound.stop();
68 }
69
70 // private inner class to handle button events
71 private class ButtonHandler implements ActionListener {
72
447
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: JApplet (12)
73 // process play, loop and stop button events
74 public void actionPerformed( ActionEvent actionEvent )
75 {
76 if ( actionEvent.getSource() == playSound )
77 currentSound.play();
78
79 else if ( actionEvent.getSource() == loopSound )
80 currentSound.loop();
81
82 else if ( actionEvent.getSource() == stopSound )
83 currentSound.stop();
84 }
85
86 } // end class ButtonHandler
87
88 } // end class LoadAudioAndPlay
448
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reflection API (1)
Represents (reflects) the classes, interfaces, and objects in the
current Java Virtual Machine
Used for writing development tools such as debuggers, class
browsers, and GUI builders
Determine the class of an object.
Get information about a class's modifiers, fields, methods, constructors,
and superclasses.
Find out what constants and method declarations belong to an interface.
Create an instance of a class whose name is not known until runtime.
Get and set the value of an object's field, even if the field name is
unknown to your program until runtime.
Invoke a method on an object, even if the method is not known until
runtime.
Create a new array, whose size and component type are not known until
runtime, and then modify the array's components.
449
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reflection API (2)
Class Description
Array Provides static methods to dynamically create and access arrays.
Constructor Provides information about, and access to, a constructor for a class.
Allows you to instantiate a class dynamically.
Field Provides information about, and dynamic access to, a field of a class
or an interface.
Method Provides information about, and access to, a single method on a class
or interface. Allows you to invoke the method dynamically.
Modifier Provides static methods and constants that allow you to get
information about the access modifiers of a class and its members.
Object get(Object obj) Returns the value of the field represented by this Field, on the
specified object.
Class getDeclaringClass() Returns the Class object representing the class or interface that
declares the field represented by this Field object.
int getModifiers() Returns the Java language modifiers for the field represented by
this Field object, as an integer.
String getName() Returns the name of the field represented by this Field object.
Class getType() Returns a Class object that identifies the declared type for the
field represented by this Field object.
void set(Object obj, Object value) Sets the field represented by this Field object on the specified
object argument to the specified new value.
455
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reflection – identifying class fields
import java.lang.reflect.*;
import java.awt.*;
public class SampleField {
Class getDeclaringClass() Returns the Class object representing the class that
declares the constructor represented by this Constructor
object.
Class[ ] getExceptionTypes() Returns an array of Class objects that represent the types
of of exceptions declared to be thrown by the underlying
constructor represented by this Constructor object.
int getModifiers() Returns the Java language modifiers for the constructor
represented by this Constructor object, as an integer.
String getName() Returns the name of this constructor, as a String.
Class[ ] getParameterTypes() Returns an array of Class objects that represent the
formal parameter types, in declaration order, of the
constructor represented by this Constructor object.
Object newInstance (Object[ ] initargs) Uses the constructor represented by this Constructor
object to create and initialize a new instance of the
constructor's declaring class, with the specified
initialization parameters.
457
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reflection – discovering class constructors
import java.lang.reflect.*;
import java.awt.*;
( )
459
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reflection – obtaining method information
import java.lang.reflect.*; Name: intersects
import java.awt.*; Return Type: boolean
public class SampleMethod { Parameter Types: double double double double
public static void main(String[] args) { Name: intersects
Return Type: boolean
Polygon p = new Polygon();
Parameter Types: java.awt.geom.Rectangle2D
showMethods(p); Name: translate
} Return Type: void
static void showMethods(Object o) { Parameter Types: int int.
Class c = o.getClass(); .
.
Method[] theMethods = c.getMethods();
for (int i = 0; i < theMethods.length; i++) {
String methodString = theMethods[i].getName();
System.out.println( "Name: " + methodString);
String returnString = theMethods[i].getReturnType().getName();
System.out.println( " Return Type: " + returnString);
Class[] parameterTypes = theMethods[i].getParameterTypes();
System.out.print( " Parameter Types: " );
for (int k = 0; k < parameterTypes.length; k ++) {
String parameterString = parameterTypes[k].getName();
System.out.print( " " + parameterString);
}
System.out.println();
}
}
} 460
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reflection – creating objects
import java.lang.reflect.*;
import java.awt.*;
463
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reflection – creating objects (arg constructors)
464
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reflection – getting field values
import java.lang.reflect.*;
import java.awt.*;
public class SampleGet {
467
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004
OOP
JCL: Reflection – invoking methods (2)
import java.lang.reflect.*;
public class SampleInvoke {
public static void main( String[] args )
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException
{
String firstWord = "Hello ";
String secondWord = "everybody.";
String bothWords = append( firstWord, secondWord );
System.out.println( bothWords );
} Hello everybody.
public static String append( String firstWord, String secondWord )
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException
{
Class c = String.class;
Class[] parameterTypes = new Class[] { String.class };
Object[] arguments = new Object[] { secondWord } ;
Method concatMethod = c.getMethod( "concat", parameterTypes );
return ( String ) concatMethod.invoke( firstWord, arguments );
}
} 468
Dipartimento di Automatica e Informatica - Politecnico di Torino Silvano Rivoira, 2004