Outline - IC
Download
Report
Transcript Outline - IC
Chapter 10 - Object-Oriented
Programming: Polymorphism
Outline
10.1
Introduction
10.2
Relationships Among Objects in an Inheritance Hierarchy
10.2.1 Invoking Superclass Methods from Subclass Objects
10.2.2 Using Superclass References with Subclass-Type
Variables
10.2.3 Subclass Method Calls via Superclass-Type Variables
10.3
Polymorphism Examples
10.4
Abstract Classes and Methods
10.5
Case Study: Inheriting Interface and Implementation
10.6
final Methods and Classes
10.7
Case Study: Payroll System Using Polymorphism
2003 Prentice Hall, Inc. All rights reserved.
1
Chapter 10 - Object-Oriented
Programming: Polymorphism
Outline
10.8
10.9
10.10
10.11
10.12
Case Study: Creating and Using Interfaces
Nested Classes
Type-Wrapper Classes for Primitive Types
(Optional Case Study) Thinking About Objects: Incorporating
Inheritance into the Elevator Simulation
(Optional) Discovering Design Patterns: Introducing Creational,
Structural and Behavioral Design Patterns
10.12.1 Creational Design Patterns
10.12.2 Structural Design Patterns
10.12.3 Behavioral Design Patterns
10.12.4 Conclusion
10.12.5 Internet and World-Wide-Web Resources
2003 Prentice Hall, Inc. All rights reserved.
2
3
10.1 Introduction
• Polymorphism
– “Program in the general”
– Treat objects in same class hierarchy as if all superclass
– Abstract class
• Common functionality
– Makes programs extensible
• New classes added easily, can still be processed
• In our examples
– Use abstract superclass Shape
• Defines common interface (functionality)
• Point, Circle and Cylinder inherit from Shape
– Class Employee for a natural example
2003 Prentice Hall, Inc. All rights reserved.
4
10.2 Relationships Among Objects in an
Inheritance Hierarchy
• Previously (Section 9.4),
– Circle inherited from Point
– Manipulated Point and Circle objects using references
to invoke methods
• This section
– Invoking superclass methods from subclass objects
– Using superclass references with subclass-type variables
– Subclass method calls via superclass-type variables
• Key concept
– subclass object can be treated as superclass object
• “is-a” relationship
• superclass is not a subclass object
2003 Prentice Hall, Inc. All rights reserved.
5
10.2.1 Invoking Superclass Methods from
Subclass Objects
• Store references to superclass and subclass objects
– Assign a superclass reference to superclass-type variable
– Assign a subclass reference to a subclass-type variable
• Both straightforward
– Assign a subclass reference to a superclass variable
• “is a” relationship
2003 Prentice Hall, Inc. All rights reserved.
6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Outline
// Fig. 10.1: HierarchyRelationshipTest1.java
// Assigning superclass and subclass references to superclass- and
// subclass-type variables.
import javax.swing.JOptionPane;
HierarchyRelation
shipTest1.java
public class HierarchyRelationshipTest1 {
public static void main( String[] args )
{
// assign superclass reference to superclass-type variable
Assign superclass
Point3 point = new Point3( 30, 50 );
Line 11
Assign superclass
reference to superclassreference
type variable
to superclass-type variable
// assign subclass reference to subclass-type variable
Circle4 circle = new Circle4( 120, 89, 2.7 );
Line 14
Assign subclass reference
to reference
Assign subclass
subclass-type variable
to subclass-type variable
// invoke toString on superclass object using superclass variable
String output = "Call Point3's toString with superclass" +
" reference to superclass object: \n" + point.toString();
// invoke toString on subclass object using subclass variable
output += "\n\nCall Circle4's toString with subclass" +
" reference to subclass object: \n" + circle.toString();
InvokeLine
toString
on
17
Invoke
toString
superclass
object
using on
superclass
object using
superclass
variable
superclass variable
Invoke toString on
subclass
object
Line
22 using
Invoke
toString on
subclass
variable
subclass object using
subclass variable
2003 Prentice Hall, Inc.
All rights reserved.
7
24
25
26
27
28
29
30
31
32
33
34
35
// invoke toString on subclass objectAssign
using subclass
superclass
variableto
reference
Point3 pointRef = circle;
superclass-type variable
output += "\n\nCall Circle4's toString with superclass" +
" reference to subclass object: \n" + pointRef.toString();
JOptionPane.showMessageDialog( null, output );
// display output
Outline
Invoke toString on
subclass
object using
HierarchyRelati
superclass
variable
onshipTest1.jav
a
System.exit( 0 );
} // end main
} // end class HierarchyRelationshipTest1
Line 25
Assign subclass
reference to
superclass-type
variable.
Line 27
Invoke toString on
subclass object using
superclass variable.
2003 Prentice Hall, Inc.
All rights reserved.
8
10.2.2 Using Superclass References with
Subclass-Type Variables
• Previous example
– Assigned subclass reference to superclass-type variable
• Circle “is a” Point
• Assign superclass reference to subclass-type
variable
– Compiler error
• No “is a” relationship
• Point is not a Circle
• Circle has data/methods that Point does not
– setRadius (declared in Circle) not declared in
Point
– Cast superclass references to subclass references
• Called downcasting
• Invoke subclass functionality
2003 Prentice Hall, Inc. All rights reserved.
9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Fig. 10.2: HierarchyRelationshipTest2.java
// Attempt to assign a superclass reference to a subclass-type variable.
public class HierarchyRelationshipTest2 {
public static void main( String[] args )
{
Point3 point = new Point3( 30, 50 );
Circle4 circle; // subclass-type variable
// assign superclass reference to subclass-type variable
circle = point; // Error: a Point3 is not a Circle4
}
} // end class HierarchyRelationshipTest2
Assigning superclass reference
to subclass-type variable causes
compiler error
Outline
HierarchyRelati
onshipTest2.jav
a
Line 12
Assigning superclass
reference to subclasstype variable causes
compiler error.
HierarchyRelationshipTest2.java:12: incompatible types
found
: Point3
required: Circle4
circle = point; // Error: a Point3 is not a Circle4
^
1 error
2003 Prentice Hall, Inc.
All rights reserved.
10
10.2.3 Subclass Method Calls via
Superclass-Type variables
• Call a subclass method with superclass reference
– Compiler error
• Subclass methods are not superclass methods
2003 Prentice Hall, Inc. All rights reserved.
11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Fig. 10.3: HierarchyRelationshipTest3.java
// Attempting to invoke subclass-only member methods through
// a superclass reference.
public class HierarchyRelationshipTest3 {
Outline
HierarchyRelati
onshipTest3.jav
a
public static void main( String[] args )
{
Point3 point;
Circle4 circle = new Circle4( 120, 89, 2.7 );
point = circle;
// aim superclass reference at subclass object
// invoke superclass (Point3) methods on subclass
// (Circle4) object through superclass reference
int x = point.getX();
int y = point.getY();
point.setX( 10 );
point.setY( 20 );
point.toString();
2003 Prentice Hall, Inc.
All rights reserved.
12
22
23
24
25
26
27
28
29
30
31
32
// attempt to invoke subclass-only (Circle4) methods on
// subclass object through superclass (Point3) reference
double radius = point.getRadius();
point.setRadius( 33.33 );
double diameter = point.getDiameter();
double circumference = point.getCircumference();
double area = point.getArea();
} // end main
} // end class HierarchyRelationshipTest3
Attempt to invoke subclassonly (Circle4) methods on
subclass object through
superclass (Point3)
reference.
Outline
HierarchyRelati
onshipTest3.jav
a
Lines 24-28
Attempt to invoke
subclass-only
(Circle4) methods
on subclass object
through superclass
(Point3) reference.
2003 Prentice Hall, Inc.
All rights reserved.
HierarchyRelationshipTest3.java:24: cannot resolve symbol
symbol : method getRadius ()
location: class Point3
double radius = point.getRadius();
^
HierarchyRelationshipTest3.java:25: cannot resolve symbol
symbol : method setRadius (double)
location: class Point3
point.setRadius( 33.33 );
^
HierarchyRelationshipTest3.java:26: cannot resolve symbol
symbol : method getDiameter ()
location: class Point3
double diameter = point.getDiameter();
^
HierarchyRelationshipTest3.java:27: cannot resolve symbol
symbol : method getCircumference ()
location: class Point3
double circumference = point.getCircumference();
^
HierarchyRelationshipTest3.java:28: cannot resolve symbol
symbol : method getArea ()
location: class Point3
double area = point.getArea();
^
5 errors
13
Outline
HierarchyRelati
onshipTest3.jav
a
2003 Prentice Hall, Inc.
All rights reserved.
14
10.3 Polymorphism Examples
• Examples
– Suppose Rectangle derives from Quadrilateral
• Rectangle more specific than Quadrilateral
• Any operation on Quadrilateral can be done on
Rectangle (i.e., perimeter, area)
• Suppose designing video game
– Superclass SpaceObject
• Subclasses Martian, SpaceShip, LaserBeam
• Contains method draw
– To refresh screen
• Send draw message to each object
• Same message has “many forms” of results
2003 Prentice Hall, Inc. All rights reserved.
15
10.3 Polymorphism Examples
• Video game example, continued
– Easy to add class Mercurian
• Extends SpaceObject
• Provides its own implementation of draw
– Programmer does not need to change code
• Calls draw regardless of object’s type
• Mercurian objects “plug right in”
2003 Prentice Hall, Inc. All rights reserved.
16
10.4 Abstract Classes and Methods
• Abstract classes
– Are superclasses (called abstract superclasses)
– Cannot be instantiated
– Incomplete
• subclasses fill in "missing pieces"
• Concrete classes
– Can be instantiated
– Implement every method they declare
– Provide specifics
2003 Prentice Hall, Inc. All rights reserved.
17
10.4 Abstract Classes and Methods (Cont.)
• Abstract classes not required, but reduce client
code dependencies
• To make a class abstract
– Declare with keyword abstract
– Contain one or more abstract methods
public abstract void draw();
– Abstract methods
• No implementation, must be overridden
2003 Prentice Hall, Inc. All rights reserved.
18
10.4 Abstract Classes and Methods (Cont.)
• Application example
– Abstract class Shape
• Declares draw as abstract method
– Circle, Triangle, Rectangle extends Shape
• Each must implement draw
– Each object can draw itself
• Iterators
– Array, ArrayList (Chapter 22)
– Walk through list elements
– Used in polymorphic programming to traverse a collection
2003 Prentice Hall, Inc. All rights reserved.
19
10.5 Case Study: Inheriting Interface and
Implementation
• Make abstract superclass Shape
– Abstract method (must be implemented)
• getName, print
• Default implementation does not make sense
– Methods may be overridden
• getArea, getVolume
– Default implementations return 0.0
• If not overridden, uses superclass default implementation
– Subclasses Point, Circle, Cylinder
2003 Prentice Hall, Inc. All rights reserved.
20
10.5 Case Study: Inheriting Interface and
Implementation
Shape
Point
Circle
Cylinder
Fig. 10.4 Shape hierarchy class diagram.
2003 Prentice Hall, Inc. All rights reserved.
21
10.6 Case Study: Inheriting Interface and
Implementation
getArea
getVolume
getName
print
Shape
0.0
0.0
= 0
= 0
Point
0.0
0.0
"Point"
[x,y]
Circle
pr2
0.0
"Circle"
center=[x,y];
radius=r
2pr2 +2prh
pr2h
"Cylinder"
center=[x,y];
radius=r;
height=h
Cylinder
Fig. 10.5 Polimorphic interface for the Shape hierarchy classes.
2003 Prentice Hall, Inc. All rights reserved.
22
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Outline
// Fig. 10.6: Shape.java
// Shape abstract-superclass declaration.
Shape.java
public abstract class Shape extends Object {
// return area of shape; 0.0 by default
public double getArea()
Keyword abstract
{
declares class Shape
return 0.0;
abstract class
}
as
// return volume of shape; 0.0 by default
public double getVolume()
{
return 0.0;
}
Line 4
Keyword abstract
declares class Shape
as abstract class
Line 19
Keyword abstract
declares method
getName as abstract
method
// abstract method, overridden by subclasses
public abstract String getName();
} // end abstract class Shape
Keyword abstract declares
method getName as abstract
method
2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Fig. 10.7: Point.java
// Point class declaration inherits from Shape.
public class Point extends Shape {
private int x; // x part of coordinate pair
private int y; // y part of coordinate pair
23
Outline
Point.java
// no-argument constructor; x and y default to 0
public Point()
{
// implicit call to Object constructor occurs here
}
// constructor
public Point( int xValue, int yValue )
{
// implicit call to Object constructor occurs here
x = xValue; // no need for validation
y = yValue; // no need for validation
}
// set x in coordinate pair
public void setX( int xValue )
{
x = xValue; // no need for validation
}
2003 Prentice Hall, Inc.
All rights reserved.
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// return x from coordinate pair
public int getX()
{
return x;
}
24
Outline
Point.java
// set y in coordinate pair
public void setY( int yValue )
{
y = yValue; // no need for validation
}
// return y from coordinate pair
public int getY()
{
return y;
}
Lines 47-50
Override abstract
method getName.
Override
abstract
method getName.
// override abstract method getName to return "Point"
public String getName()
{
return "Point";
}
// override toString to return String representation of Point
public String toString()
{
return "[" + getX() + ", " + getY() + "]";
}
} // end class Point
2003 Prentice Hall, Inc.
All rights reserved.
25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Fig. 10.8: Circle.java
// Circle class inherits from Point.
public class Circle extends Point {
private double radius; // Circle's radius
Outline
Circle.java
// no-argument constructor; radius defaults to 0.0
public Circle()
{
// implicit call to Point constructor occurs here
}
// constructor
public Circle( int x, int y, double radiusValue )
{
super( x, y ); // call Point constructor
setRadius( radiusValue );
}
// set radius
public void setRadius( double radiusValue )
{
radius = ( radiusValue < 0.0 ? 0.0 : radiusValue );
}
2003 Prentice Hall, Inc.
All rights reserved.
26
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// return radius
public double getRadius()
{
return radius;
}
// calculate and return diameter
public double getDiameter()
{
return 2 * getRadius();
}
Outline
Circle.java
Lines 45-48
Override method
getArea to return
circle area.
// calculate and return circumference
Override method
public double getCircumference()
getArea to
{
return circle area
return Math.PI * getDiameter();
}
// override method getArea to return Circle area
public double getArea()
{
return Math.PI * getRadius() * getRadius();
}
2003 Prentice Hall, Inc.
All rights reserved.
27
50
51
52
53
54
55
56
57
58
59
60
61
62
// override abstract method getName to return "Circle"
public String getName()
Override
{
return "Circle";
abstract
}
method getName
// override toString to return String representation of Circle
public String toString()
{
return "Center = " + super.toString() + "; Radius = " + getRadius();
}
Outline
Circle.java
Lines 51-54
Override abstract
method getName.
} // end class Circle
2003 Prentice Hall, Inc.
All rights reserved.
28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Fig. 10.9: Cylinder.java
// Cylinder class inherits from Circle.
public class Cylinder extends Circle {
private double height; // Cylinder's height
Outline
Cylinder.java
// no-argument constructor; height defaults to 0.0
public Cylinder()
{
// implicit call to Circle constructor occurs here
}
// constructor
public Cylinder( int x, int y, double radius, double heightValue )
{
super( x, y, radius ); // call Circle constructor
setHeight( heightValue );
}
// set Cylinder's height
public void setHeight( double heightValue )
{
height = ( heightValue < 0.0 ? 0.0 : heightValue );
}
2003 Prentice Hall, Inc.
All rights reserved.
29
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// get Cylinder's height
public double getHeight()
{
return height;
}
Override method
getArea to
return cylinder
area
// override abstract method getArea to Override
return Cylinder
method area
public double getArea()
getVolume to
{
return cylinder
return 2 * super.getArea() + getCircumference() * getHeight();
volume
}
// override abstract method getVolume to return Cylinder volume
public double getVolume()
{
return super.getArea() * getHeight();
}
// override abstract method getName to return "Cylinder"
public String getName()
Override
{
abstract
return "Cylinder";
method getName
}
Outline
Cylinder.java
Lines 33-36
Override method
getArea to return
cylinder area
Lines 39-42
Override method
getVolume to return
cylinder volume
Lines 45-48
Override abstract
method getName
2003 Prentice Hall, Inc.
All rights reserved.
30
49
50
51
52
53
54
55
56
Outline
// override toString to return String representation of Cylinder
public String toString()
{
return super.toString() + "; Height = " + getHeight();
}
Cylinder.java
} // end class Cylinder
2003 Prentice Hall, Inc.
All rights reserved.
31
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Fig. 10.10: AbstractInheritanceTest.java
// Driver for shape, point, circle, cylinder hierarchy.
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
Outline
AbstractInherit
anceTest.java
public class AbstractInheritanceTest {
public static void main( String args[] )
{
// set floating-point number format
DecimalFormat twoDigits = new DecimalFormat( "0.00" );
// create Point, Circle and Cylinder objects
Point point = new Point( 7, 11 );
Circle circle = new Circle( 22, 8, 3.5 );
Cylinder cylinder = new Cylinder( 20, 30, 3.3, 10.75 );
// obtain name and string representation of each object
String output = point.getName() + ": " + point + "\n" +
circle.getName() + ": " + circle + "\n" +
cylinder.getName() + ": " + cylinder + "\n";
Shape arrayOfShapes[] = new Shape[ 3 ];
// create Shape array
2003 Prentice Hall, Inc.
All rights reserved.
32
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// aim arrayOfShapes[ 0 ] at subclass Point object
arrayOfShapes[ 0 ] = point;
Outline
// aim arrayOfShapes[ 1 ] at subclass CircleCreate
objectan
arrayOfShapes[ 1 ] = circle;
array of
AbstractInherit
Loop
through
generic Shape objects
anceTest.java
arrayOfShapes to get
// aim arrayOfShapes[ 2 ] at subclass Cylinder object
name, string representation,
Lines 26-32
arrayOfShapes[ 2 ] = cylinder;
area and volume of Create
every an array of
shape in array
// loop through arrayOfShapes to get name, string
generic Shape
// representation, area and volume of every Shape in array
for ( int i = 0; i < arrayOfShapes.length; i++ ) {
output += "\n\n" + arrayOfShapes[ i ].getName() + ": " +
arrayOfShapes[ i ].toString() + "\nArea = " +
twoDigits.format( arrayOfShapes[ i ].getArea() ) +
"\nVolume = " +
twoDigits.format( arrayOfShapes[ i ].getVolume() );
}
JOptionPane.showMessageDialog( null, output );
System.exit( 0 );
// display output
objects
Lines 36-42
Loop through
arrayOfShapes to
get name, string
representation, area
and volume of every
shape in array
} // end main
} // end class AbstractInheritanceTest
2003 Prentice Hall, Inc.
All rights reserved.
33
2003 Prentice Hall, Inc. All rights reserved.
34
10.6 final Methods and Classes
• final methods
– Cannot be overridden
– private methods are implicitly final
– static methods are implicitly final
• final classes
– Cannot be superclasses
– Methods in final classes are implicitly final
– e.g., class String
2003 Prentice Hall, Inc. All rights reserved.
35
10.7 Case Study: Payroll System Using
Polymorphism
• Create a payroll program
– Use abstract methods and polymorphism
• Problem statement
– 4 types of employees, paid weekly
•
•
•
•
Salaried (fixed salary, no matter the hours)
Hourly (overtime [>40 hours] pays time and a half)
Commission (paid percentage of sales)
Base-plus-commission (base salary + percentage of sales)
– Boss wants to raise pay by 10%
2003 Prentice Hall, Inc. All rights reserved.
36
10.9 Case Study: Payroll System Using
Polymorphism
• Superclass Employee
– Abstract method earnings (returns pay)
• abstract because need to know employee type
• Cannot calculate for generic employee
– Other classes extend Employee
Employee
SalariedEmployee
CommissionEmployee
BasePlusCommissionEmployee
2003 Prentice Hall, Inc. All rights reserved.
HourlyEmployee
37
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Outline
// Fig. 10.12: Employee.java
// Employee abstract superclass.
public abstract class Employee {
private String firstName;
private String lastName;
private String socialSecurityNumber;
Declares class Employee
as abstract class.
// constructor
public Employee( String first, String last, String ssn )
{
firstName = first;
lastName = last;
socialSecurityNumber = ssn;
}
Employee.java
Line 4
Declares class
Employee as
abstract class.
// set first name
public void setFirstName( String first )
{
firstName = first;
}
2003 Prentice Hall, Inc.
All rights reserved.
38
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// return first name
public String getFirstName()
{
return firstName;
}
Outline
Employee.java
// set last name
public void setLastName( String last )
{
lastName = last;
}
// return last name
public String getLastName()
{
return lastName;
}
// set social security number
public void setSocialSecurityNumber( String number )
{
socialSecurityNumber = number; // should validate
}
2003 Prentice Hall, Inc.
All rights reserved.
39
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
Outline
// return social security number
public String getSocialSecurityNumber()
{
return socialSecurityNumber;
}
Employee.java
// return String representation of Employee object
public String toString()
{
return getFirstName() + " " + getLastName() +
"\nsocial security number: " + getSocialSecurityNumber();
}
// abstract method overridden by subclasses
public abstract double earnings();
Line 61
Abstract method
overridden by
subclasses.
Abstract method
overridden by subclasses
} // end abstract class Employee
2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Fig. 10.13: SalariedEmployee.java
// SalariedEmployee class extends Employee.
40
Outline
public class SalariedEmployee extends Employee {
private double weeklySalary;
// constructor
Use superclass
public SalariedEmployee( String first, String last,
basic fields.
String socialSecurityNumber, double salary )
{
super( first, last, socialSecurityNumber );
setWeeklySalary( salary );
}
SalariedEmploye
e.java
constructor for
Line 11
Use superclass
constructor for basic
fields.
// set salaried employee's salary
public void setWeeklySalary( double salary )
{
weeklySalary = salary < 0.0 ? 0.0 : salary;
}
// return salaried employee's salary
public double getWeeklySalary()
{
return weeklySalary;
}
2003 Prentice Hall, Inc.
All rights reserved.
41
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// calculate salaried employee's pay;
// override abstract method earnings in Employee
public double earnings()
{
return getWeeklySalary();
}
Must implement abstract
method earnings.
// return String representation of SalariedEmployee object
public String toString()
{
return "\nsalaried employee: " + super.toString();
}
Outline
SalariedEmploye
e.java
Lines 29-32
Must implement
abstract method
earnings.
} // end class SalariedEmployee
2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Fig. 10.14: HourlyEmployee.java
// HourlyEmployee class extends Employee.
public class HourlyEmployee extends Employee {
private double wage;
// wage per hour
private double hours; // hours worked for week
42
Outline
HourlyEmployee.
java
// constructor
public HourlyEmployee( String first, String last,
String socialSecurityNumber, double hourlyWage, double hoursWorked )
{
super( first, last, socialSecurityNumber );
setWage( hourlyWage );
setHours( hoursWorked );
}
// set hourly employee's wage
public void setWage( double wageAmount )
{
wage = wageAmount < 0.0 ? 0.0 : wageAmount;
}
// return wage
public double getWage()
{
return wage;
}
2003 Prentice Hall, Inc.
All rights reserved.
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// set hourly employee's hours worked
public void setHours( double hoursWorked )
{
hours = ( hoursWorked >= 0.0 && hoursWorked <= 168.0 ) ?
hoursWorked : 0.0;
}
// return hours worked
public double getHours()
{
return hours;
}
43
Outline
HourlyEmployee.
java
Lines 44-50
Must implement
abstract method
earnings.
// calculate hourly employee's pay;
// override abstract method earnings in Employee
public double earnings()
Must implement abstract
{
method earnings.
if ( hours <= 40 ) // no overtime
return wage * hours;
else
return 40 * wage + ( hours - 40 ) * wage * 1.5;
}
// return String representation of HourlyEmployee object
public String toString()
{
return "\nhourly employee: " + super.toString();
}
} // end class HourlyEmployee
2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Fig. 10.15: CommissionEmployee.java
// CommissionEmployee class extends Employee.
public class CommissionEmployee extends Employee {
private double grossSales;
// gross weekly sales
private double commissionRate; // commission percentage
44
Outline
CommissionEmplo
yee.java
// constructor
public CommissionEmployee( String first, String last,
String socialSecurityNumber,
double grossWeeklySales, double percent )
{
super( first, last, socialSecurityNumber );
setGrossSales( grossWeeklySales );
setCommissionRate( percent );
}
// set commission employee's rate
public void setCommissionRate( double rate )
{
commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;
}
// return commission employee's rate
public double getCommissionRate()
{
return commissionRate;
}
2003 Prentice Hall, Inc.
All rights reserved.
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
45
Outline
// set commission employee's weekly base salary
public void setGrossSales( double sales )
{
grossSales = sales < 0.0 ? 0.0 : sales;
}
CommissionEmplo
yee.java
// return commission employee's gross sales amount
public double getGrossSales()
{
return grossSales;
}
Lines 44-47
Must implement
abstract method
earnings.
// calculate commission employee'sMust
pay; implement abstract
// override abstract method earnings
in Employee
method
earnings.
public double earnings()
{
return getCommissionRate() * getGrossSales();
}
// return String representation of CommissionEmployee object
public String toString()
{
return "\ncommission employee: " + super.toString();
}
} // end class CommissionEmployee
2003 Prentice Hall, Inc.
All rights reserved.
46
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Fig. 10.16: BasePlusCommissionEmployee.java
// BasePlusCommissionEmployee class extends CommissionEmployee.
public class BasePlusCommissionEmployee extends CommissionEmployee {
private double baseSalary; // base salary per week
// constructor
public BasePlusCommissionEmployee( String first, String last,
String socialSecurityNumber, double grossSalesAmount,
double rate, double baseSalaryAmount )
{
super( first, last, socialSecurityNumber, grossSalesAmount, rate );
setBaseSalary( baseSalaryAmount );
}
Outline
BasePlusCommiss
ionEmployee.jav
a
// set base-salaried commission employee's base salary
public void setBaseSalary( double salary )
{
baseSalary = salary < 0.0 ? 0.0 : salary;
}
// return base-salaried commission employee's base salary
public double getBaseSalary()
{
return baseSalary;
}
2003 Prentice Hall, Inc.
All rights reserved.
47
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// calculate base-salaried commission employee's earnings;
// override method earnings in CommissionEmployee
public double earnings()
Override method earnings
{
in CommissionEmployee
return getBaseSalary() + super.earnings();
}
// return String representation of BasePlusCommissionEmployee
public String toString()
{
return "\nbase-salaried commission employee: " +
super.getFirstName() + " " + super.getLastName() +
"\nsocial security number: " + super.getSocialSecurityNumber();
}
Outline
BasePlusCommiss
ionEmployee.jav
a
Lines 30-33
Override method
earnings in
CommissionEmplo
yee
} // end class BasePlusCommissionEmployee
2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Fig. 10.17: PayrollSystemTest.java
// Employee hierarchy test program.
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class PayrollSystemTest {
48
Outline
PayrollSystemTe
st.java
public static void main( String[] args )
{
DecimalFormat twoDigits = new DecimalFormat( "0.00" );
// create Employee array
Employee employees[] = new Employee[ 4 ];
// initialize array with Employees
employees[ 0 ] = new SalariedEmployee( "John", "Smith",
"111-11-1111", 800.00 );
employees[ 1 ] = new CommissionEmployee( "Sue", "Jones",
"222-22-2222", 10000, .06 );
employees[ 2 ] = new BasePlusCommissionEmployee( "Bob", "Lewis",
"333-33-3333", 5000, .04, 300 );
employees[ 3 ] = new HourlyEmployee( "Karen", "Price",
"444-44-4444", 16.75, 40 );
String output = "";
2003 Prentice Hall, Inc.
All rights reserved.
49
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// generically process each element in array employees
for ( int i = 0; i < employees.length; i++ ) {
output += employees[ i ].toString();
Outline
PayrollSystemTe
// determine whether element is a BasePlusCommissionEmployee
st.java
if ( employees[ i ] instanceof BasePlusCommissionEmployee ) {
Determine whether element is a
Line 32
BasePlusCommissionEmpl
// downcast Employee reference to
Determine whether
oyee
// BasePlusCommissionEmployee reference
element is a
BasePlusCommissionEmployee currentEmployee =
BasePlusCommiss
( BasePlusCommissionEmployee ) employees[ i ];
Downcast Employee reference to ionEmployee
BasePlusCommissionEmployee
double oldBaseSalary = currentEmployee.getBaseSalary();
output += "\nold base salary: reference
$" + oldBaseSalary;
Line 37
Downcast Employee
currentEmployee.setBaseSalary( 1.10 * oldBaseSalary );
reference to
output += "\nnew base salary with 10% increase is: $" +
BasePlusCommiss
currentEmployee.getBaseSalary();
ionEmployee
reference
} // end if
output += "\nearned $" + employees[ i ].earnings() + "\n";
} // end for
2003 Prentice Hall, Inc.
All rights reserved.
50
52
53
54
55
56
57
58
59
60
61
62
// get type name of each object in employees array
for ( int j = 0; j < employees.length; j++ )
output += "\nEmployee " + j + " is a " +
employees[ j ].getClass().getName();
JOptionPane.showMessageDialog( null, output );
System.exit( 0 );
} // end main
} // end class PayrollSystemTest
Outline
Get type name of eachPayrollSystemTe
object in employeesst.java
// display output
array
Lines 53-55
Get type name of each
object in employees
array
2003 Prentice Hall, Inc.
All rights reserved.
51
10.8 Case Study: Creating and Using
Interfaces
• Use interface Shape
– Replace abstract class Shape
• Interface
– Declaration begins with interface keyword
– Classes implement an interface (and its methods)
– Contains public abstract methods
• Classes (that implement the interface) must implement these
methods
2003 Prentice Hall, Inc. All rights reserved.
52
1
2
3
4
5
6
7
8
9
// Fig. 10.18: Shape.java
// Shape interface declaration.
public interface
public double
public double
public String
Shape {
getArea();
getVolume();
getName();
} // end interface Shape
Classes that implement Shape
must implement these methods
Outline
Shape.java
// calculate area
// calculate volume
// return shape name
Lines 5-7
Classes that
implement Shape
must implement these
methods
2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Fig. 10.19: Point.java
// Point class declaration implements interface Shape.
public class Point extends Object implements Shape {
private int x; // x part of coordinate pair
private int y; // y part of coordinate pair
// no-argument constructor; x and y default to 0
Point implements
public Point()
{
// implicit call to Object constructor occurs here
}
53
Outline
Point.java
Line 4
Point implements
interface Shape
interface Shape
// constructor
public Point( int xValue, int yValue )
{
// implicit call to Object constructor occurs here
x = xValue; // no need for validation
y = yValue; // no need for validation
}
// set x in coordinate pair
public void setX( int xValue )
{
x = xValue; // no need for validation
}
2003 Prentice Hall, Inc.
All rights reserved.
54
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// return x from coordinate pair
public int getX()
{
return x;
}
Outline
Point.java
// set y in coordinate pair
public void setY( int yValue )
{
y = yValue; // no need for validation
}
// return y from coordinate pair
public int getY()
{
return y;
}
2003 Prentice Hall, Inc.
All rights reserved.
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// declare abstract method getArea
public double getArea()
{
return 0.0;
}
// declare abstract method getVolume
public double getVolume()
{
return 0.0;
}
55
Outline
Point.java
Lines 47-59
Implement methods specified
Implement methods
by interface Shape
specified by interface
Shape
// override abstract method getName to return "Point"
public String getName()
{
return "Point";
}
// override toString to return String representation of Point
public String toString()
{
return "[" + getX() + ", " + getY() + "]";
}
} // end class Point
2003 Prentice Hall, Inc.
All rights reserved.
56
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Fig. 10.20: InterfaceTest.java
// Test Point, Circle, Cylinder hierarchy with interface Shape.
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
Outline
InterfaceTest.j
ava
public class InterfaceTest {
public static void main( String args[] )
{
// set floating-point number format
DecimalFormat twoDigits = new DecimalFormat( "0.00" );
Line 23
Create Shape array
// create Point, Circle and Cylinder objects
Point point = new Point( 7, 11 );
Circle circle = new Circle( 22, 8, 3.5 );
Cylinder cylinder = new Cylinder( 20, 30, 3.3, 10.75 );
// obtain name and string representation of each object
String output = point.getName() + ": " + point + "\n" +
Create Shape array
circle.getName() + ": " + circle + "\n" +
cylinder.getName() + ": " + cylinder + "\n";
Shape arrayOfShapes[] = new Shape[ 3 ];
// create Shape array
2003 Prentice Hall, Inc.
All rights reserved.
57
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// aim arrayOfShapes[ 0 ] at subclass Point object
arrayOfShapes[ 0 ] = point;
Outline
// aim arrayOfShapes[ 1 ] at subclass Circle object
arrayOfShapes[ 1 ] = circle;
InterfaceTest.j
ava
Loop through arrayOfShapes to
// aim arrayOfShapes[ 2 ] at subclass Cylinder
get name,object
string representation, area
arrayOfShapes[ 2 ] = cylinder;
and volume of every shape in arrayLines 36-42
Loop through
// loop through arrayOfShapes to get name, string
arrayOfShapes to
// representation, area and volume of every Shape in array
get name, string
for ( int i = 0; i < arrayOfShapes.length; i++ ) {
representation, area
output += "\n\n" + arrayOfShapes[ i ].getName() + ": " +
arrayOfShapes[ i ].toString() + "\nArea = " +
and volume of every
twoDigits.format( arrayOfShapes[ i ].getArea() ) +
shape in array.
"\nVolume = " +
twoDigits.format( arrayOfShapes[ i ].getVolume() );
}
JOptionPane.showMessageDialog( null, output );
// display output
System.exit( 0 );
} // end main
} // end class InterfaceTest
2003 Prentice Hall, Inc.
All rights reserved.
58
Outline
InterfaceTest.j
ava
2003 Prentice Hall, Inc.
All rights reserved.
59
10.8 Case Study: Creating and Using
Interfaces (Cont.)
• Implementing Multiple Interface
– Provide common-separated list of interface names after
keyword implements
• Declaring Constants with Interfaces
– public interface
public static
public static
public static
}
2003 Prentice Hall, Inc. All rights reserved.
Constants
final int
final int
final int
{
ONE = 1;
TWO = 2;
THREE = 3;
60
10.9 Nested Classes
• Top-level classes
– Not declared inside a class or a method
• Nested classes
– Declared inside other classes
– Inner classes
• Non-static nested classes
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Fig. 10.21: Time.java
// Time class declaration with set and get methods.
import java.text.DecimalFormat;
public class Time {
private int hour;
private int minute;
private int second;
61
Outline
Time.java
// 0 - 23
// 0 - 59
// 0 - 59
// one formatting object to share in toString and toUniversalString
private static DecimalFormat twoDigits = new DecimalFormat( "00" );
// Time constructor initializes each instance variable to zero;
// ensures that Time object starts in a consistent state
public Time()
{
this( 0, 0, 0 ); // invoke Time constructor with three arguments
}
// Time constructor: hour supplied, minute and second defaulted to 0
public Time( int h )
{
this( h, 0, 0 ); // invoke Time constructor with three arguments
}
2003 Prentice Hall, Inc.
All rights reserved.
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Time constructor: hour and minute supplied, second defaulted to 0
public Time( int h, int m )
{
this( h, m, 0 ); // invoke Time constructor with three arguments
}
62
Outline
Time.java
// Time constructor: hour, minute and second supplied
public Time( int h, int m, int s )
{
setTime( h, m, s );
}
// Time constructor: another Time3 object supplied
public Time( Time time )
{
// invoke Time constructor with three arguments
this( time.getHour(), time.getMinute(), time.getSecond() );
}
// Set Methods
// set a new time value using universal time; perform
// validity checks on data; set invalid values to zero
public void setTime( int h, int m, int s )
{
setHour( h );
// set the hour
setMinute( m ); // set the minute
setSecond( s ); // set the second
}
2003 Prentice Hall, Inc.
All rights reserved.
63
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// validate and set hour
public void setHour( int h )
{
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
}
Outline
Time.java
// validate and set minute
public void setMinute( int m )
{
minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
}
// validate and set second
public void setSecond( int s )
{
second = ( ( s >= 0 && s < 60 ) ? s : 0 );
}
// Get Methods
// get hour value
public int getHour()
{
return hour;
}
2003 Prentice Hall, Inc.
All rights reserved.
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// get minute value
public int getMinute()
{
return minute;
}
// get second value
public int getSecond()
{
return second;
}
64
Outline
Time.java
Lines 101-107
Override method
java.lang.Objec
t.toString
// convert to String in universal-time format
Override method
public String toUniversalString()
{
java.lang.Object.toString
return twoDigits.format( getHour() ) + ":" +
twoDigits.format( getMinute() ) + ":" +
twoDigits.format( getSecond() );
}
// convert to String in standard-time format
public String toString()
{
return ( ( getHour() == 12 || getHour() == 0 ) ?
12 : getHour() % 12 ) + ":" + twoDigits.format( getMinute() ) +
":" + twoDigits.format( getSecond() ) +
( getHour() < 12 ? " AM" : " PM" );
}
} // end class Time
2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Fig. 10.22: TimeTestWindow.java
JFrame
provides
basic window
// Inner class declarations used to create
event
handlers.
attributes and behaviors
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
65
Outline
public class TimeTestWindow extends JFrame {
private Time time;
private JLabel hourLabel, minuteLabel, secondLabel;
private JTextField hourField, minuteField, secondField, displayField;
private JButton exitButton;
// set up GUI
public TimeTestWindow()
{
// call JFrame constructor to set
title bar
string
Instantiate
Time
object
super( "Inner Class Demonstration" );
time = new Time();
Line 7
JFrame provides
basic window
attributes and
JFrame (unlike JApplet)
behaviors
has constructor
// create Time object
// use inherited method getContentPane to get window's content pane
Container container = getContentPane();
container.setLayout( new FlowLayout() ); // change layout
// set up hourLabel and hourField
hourLabel = new JLabel( "Set Hour" );
hourField = new JTextField( 10 );
container.add( hourLabel );
container.add( hourField );
TimeTestWindow.
java
Line 17
JFrame (unlike
JApplet) has
constructor
Line 19
Instantiate Time
object
2003 Prentice Hall, Inc.
All rights reserved.
66
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
Outline
// set up minuteLabel and minuteField
minuteLabel = new JLabel( "Set Minute" );
minuteField = new JTextField( 10 );
container.add( minuteLabel );
container.add( minuteField );
TimeTestWindow.
java
// set up secondLabel and secondField
secondLabel = new JLabel( "Set Second" );
secondField = new JTextField( 10 );
container.add( secondLabel );
container.add( secondField );
// set up displayField
displayField = new JTextField( 30 );
displayField.setEditable( false );
container.add( displayField );
// set up exitButton
exitButton = new JButton( "Exit" );
container.add( exitButton );
Line 53
Instantiate object of
inner-class that
implements
ActionListener.
Instantiate object of innerclass that implements
ActionListener
// create an instance of inner class ActionEventHandler
ActionEventHandler handler = new ActionEventHandler();
2003 Prentice Hall, Inc.
All rights reserved.
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// register event handlers; the object referenced by handler
67
// is the ActionListener, which contains method actionPerformed
// that will be called to handle action events generated by
// hourField, minuteField, secondField and exitButton
hourField.addActionListener( handler );
TimeTestWindow.
Register
minuteField.addActionListener( handler );
java
secondField.addActionListener( handler );
ActionEventHandler
exitButton.addActionListener( handler );
with GUI components
Outline
} // end constructor
// display time in displayField
public void displayTime()
{
displayField.setText( "The time is: " + time );
}
Lines 59-62
Register
ActionEventHand
ler with GUI
components.
// launch application: create, size and display TimeTestWindow;
// when main terminates, program continues execution because a
// window is displayed by the statements in main
public static void main( String args[] )
{
TimeTestWindow window = new TimeTestWindow();
window.setSize( 400, 140 );
window.setVisible( true );
} // end main
2003 Prentice Hall, Inc.
All rights reserved.
68
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// inner class declaration for handling JTextField and JButton events
private class ActionEventHandler implements ActionListener {
// method to handle action events
public void actionPerformed( ActionEvent event )
Declare inner class that implements
{
// user pressed exitButton
ActionListener
interface
When user presses JButton
or Enter key,
if ( event.getSource() == exitButton )
method actionPerformed
is invoked
System.exit( 0 );
// terminate the application
Outline
TimeTestWindow.
java
Line 85
Declare inner class
Must implement method actionPerformed
// user pressed Enter key in hourField
Line 88
else if ( event.getSource() == hourField ) { of ActionListener
Must implement
time.setHour( Integer.parseInt(
event.getActionCommand() ) );
method
Determine action
depending
hourField.setText( "" );
actionPerformed
on where event
originated
}
// user pressed Enter key in minuteField
else if ( event.getSource() == minuteField ) {
time.setMinute( Integer.parseInt(
event.getActionCommand() ) );
minuteField.setText( "" );
}
Line 88
When user presses
button or key, method
actionPerformed
is invoked
Lines 91-113
Determine action
depending on where
event originated
2003 Prentice Hall, Inc.
All rights reserved.
69
108
// user pressed Enter key in secondField
109
else if ( event.getSource() == secondField ) {
110
time.setSecond( Integer.parseInt(
111
event.getActionCommand() ) );
112
secondField.setText( "" );
113
}
114
115
displayTime(); // call outer class's method
116
117
} // end method actionPerformed
118
119
} // end inner class ActionEventHandler
120
121 } // end class TimeTestWindow
Outline
TimeTestWindow.
java
2003 Prentice Hall, Inc.
All rights reserved.
70
Outline
TimeTestWindow.
java
2003 Prentice Hall, Inc.
All rights reserved.
71
10.9 Nested Classes (cont.)
• Anonymous inner class
– Declared inside a method of a class
– Has no name
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Fig. 10.23: TimeTestWindow2.java
// Demonstrating the Time class set and get methods
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TimeTestWindow2 extends JFrame {
private Time time;
private JLabel hourLabel, minuteLabel, secondLabel;
private JTextField hourField, minuteField, secondField, displayField;
72
Outline
TimeTestWindow.
java
// constructor
public TimeTestWindow2()
{
// call JFrame constructor to set title bar string
super( "Anonymous Inner Class Demonstration" );
time = new Time();
createGUI();
registerEventHandlers();
// create Time object
// set up GUI
// set up event handling
}
// create GUI components and attach to content pane
private void createGUI()
{
Container container = getContentPane();
container.setLayout( new FlowLayout() );
2003 Prentice Hall, Inc.
All rights reserved.
73
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
hourLabel = new JLabel( "Set Hour" );
hourField = new JTextField( 10 );
container.add( hourLabel );
container.add( hourField );
minuteLabel = new JLabel( "Set minute" );
minuteField = new JTextField( 10 );
container.add( minuteLabel );
container.add( minuteField );
Outline
TimeTestWindow.
java
secondLabel = new JLabel( "Set Second" );
secondField = new JTextField( 10 );
container.add( secondLabel );
container.add( secondField );
displayField = new JTextField( 30 );
displayField.setEditable( false );
container.add( displayField );
} // end method createGUI
// register event handlers for hourField, minuteField and secondField
private void registerEventHandlers()
{
2003 Prentice Hall, Inc.
All rights reserved.
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// register hourField event handler
hourField.addActionListener(
new ActionListener() {
//
74
Define anonymous inner class that
anonymous
inner class
implements
ActionListener
public void actionPerformed( ActionEvent event )
{
time.setHour( Integer.parseInt(
event.getActionCommand() ) );
hourField.setText( "" );
displayTime();
Inner
}
} // end anonymous inner class
); // end call to addActionListener for
// register minuteField event handler
minuteField.addActionListener(
new ActionListener() {
Outline
TimeTestWindow.
java
Line 54
Pass Actionclass implements method
Listener to GUI
actionPerformedcomponent’s
of
method
ActionListeneraddActionListener
hourField Pass ActionListener as
argument to GUI component’s
Line 56
method addActionListener
Define anonymous
inner class
// anonymous inner class
public void actionPerformed( ActionEvent event )
{
Repeat process for JTextField
time.setMinute( Integer.parseInt(
minuteField
event.getActionCommand() ) );
minuteField.setText( "" );
displayTime();
}
Lines 58-64
Inner class
implements method
actionPerformed
Lines 71-85
Repeat process for
minuteField
2003 Prentice Hall, Inc.
All rights reserved.
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
75
Outline
} // end anonymous inner class
); // end call to addActionListener for minuteField
secondField.addActionListener(
new ActionListener() {
TimeTestWindow.
java
Repeat process for JTextField
secondField
// anonymous inner class
public void actionPerformed( ActionEvent event )
{
time.setSecond( Integer.parseInt(
event.getActionCommand() ) );
secondField.setText( "" );
displayTime();
}
Line 87-101
Repeat process for
JTextField
secondField
} // end anonymous inner class
); // end call to addActionListener for secondField
} // end method registerEventHandlers
// display time in displayField
public void displayTime()
{
displayField.setText( "The time is: " + time );
}
2003 Prentice Hall, Inc.
All rights reserved.
110
76
111
// create TimeTestWindow2 object, register for its window events
112
// and display it to begin application's execution
113
public static void main( String args[] )
114
{
TimeTestWindow.
115
TimeTestWindow2 window = new TimeTestWindow2();
java
116
117
// register listener for windowClosing event
Line 121-129
118
window.addWindowListener(
Declare
Declare anonymous inner
classanonymous
119
inner class that
that extends WindowsAdapter
120
// anonymous inner class for windowClosing event
extends
to enable closing of JFrame
121
new WindowAdapter() {
WindowsAdapter
122
to enable closing of
123
// terminate application when user closes window
124
public void windowClosing( WindowEvent event )
JFrame
125
{
126
System.exit( 0 );
127
}
128
129
} // end anonymous inner class
130
131
); // end call to addWindowListener for window
132
133
window.setSize( 400, 105 );
134
window.setVisible( true );
135
136
} // end main
137
138 } // end class TimeTestWindow2
2003 Prentice Hall, Inc.
All rights reserved.
Outline
77
Outline
TimeTestWindow.
java
2003 Prentice Hall, Inc.
All rights reserved.
78
10.9 Nested Classes (Cont.)
• Notes on nested classes
– Compiling class that contains nested class
• Results in separate .class file
– Inner classes with names can be declared as
• public, protected, private or package access
– Access outer class’s this reference
OuterClassName.this
– Outer class is responsible for creating inner class objects
– Nested classes can be declared static
2003 Prentice Hall, Inc. All rights reserved.
79
10.10 Type-Wrapper Classes for Primitive
Types
• Type-wrapper class
– Each primitive type has one
• Character, Byte, Integer, Boolean, etc.
– Enable to represent primitive as Object
• Primitive types can be processed polymorphically
– Declared as final
– Many methods are declared static
2003 Prentice Hall, Inc. All rights reserved.
10.11 (Optional Case Study) Thinking About
Objects: Incorporating Inheritance into the
Elevator Simulation
• Our design can benefit from inheritance
– Examine sets of classes
– Look for commonality between/among sets
• Extract commonality into superclass
– Subclasses inherits this commonality
2003 Prentice Hall, Inc. All rights reserved.
80
81
10.11 Thinking About Objects (cont.)
• ElevatorButton and FloorButton
–
–
–
–
Treated as separate classes
Both have attribute pressed
Both have operations pressButton and resetButton
Move attribute and operations into superclass Button?
2003 Prentice Hall, Inc. All rights reserved.
82
FloorButton
ElevatorButton
- pressed : Boolean = false
- pressed : Boolean = false
+ resetButton( ) : void
+ pressButton( ) : void
+ resetButton( ) : void
+ pressButton( ) : void
Fig. 10.24 Attributes and operations of classes FloorButton and ElevatorButton.
2003 Prentice Hall, Inc. All rights reserved.
83
10.11 Thinking About Objects (cont.)
• ElevatorButton and FloorButton
– FloorButton requests Elevator to move
– ElevatorButton signals Elevator to move
– Neither button orders the Elevator to move
• Elevator responds depending on its state
– Both buttons signal Elevator to move
• Different objects of the same class
– They are objects of class Button
– Combine (not inherit) ElevatorButton and
FloorButton into class Button
2003 Prentice Hall, Inc. All rights reserved.
84
10.11 Thinking About Objects (cont.)
• Representing location of Person
– On what Floor is Person when riding Elevator?
– Both Floor and Elevator are types of locations
• Share int attribute capacity
• Inherit from abstract superclass Location
– Contains String locationName representing location
• “firstFloor”
• “secondFloor”
• “elevator”
– Person now contains Location reference
• References Elevator when person is in elevator
• References Floor when person is on floor
2003 Prentice Hall, Inc. All rights reserved.
85
Location
- locationName : String
- capacity : Integer = 1 {frozen}
# setLocationName( String ) : void
+ getLocationName( ) : String
+ getCapacity( ) : Integer
+ getButton( ) : Button
+ getDoor( ) : Door
Elevator
- moving : Boolean = false
- summoned : Boolean = false
- currentFloor : Integer
- destinationFloor : Integer
- travelTime : Integer = 5
Floor
+ getButton( ) : Button
+ getDoor( ) : Door
+ ride( ) : void
+ requestElevator( ) : void
+ enterElevator( ) : void
+ exitElevator( ) : void
+ departElevator( ) : void
+ getButton( ) : Button
+ getDoor( ) : Door
Fig. 10.25 Class diagram modeling generalization of superclass Location and
subclasses Elevator and Floor.
2003 Prentice Hall, Inc. All rights reserved.
86
9.23 Thinking About Objects (cont.)
• ElevatorDoor and FloorDoor
– Both have attribute open
– Both have operations openDoor and closeDoor
– Different behavior
• Rename FloorDoor to Door
• ElevatorDoor is “special case” of Door
– Override methods openDoor and closeDoor
2003 Prentice Hall, Inc. All rights reserved.
87
FloorDoor
ElevatorDoor
- open : Boolean = false
- open : Boolean = false
+ openDoor( ) : void
+ closeDoor( ) : void
+ openDoor( ) : void
+ closeDoor( ) : void
Fig. 10.26 Attributes and operations of classes FloorDoor and ElevatorDoor.
Door
ElevatorDoor
- open : Boolean = false
+ openDoor( ) : void
+ closeDoor( ) : void
+ openDoor( ) : void
+ closeDoor( ) : void
Fig. 10.27 Generalization of superclass Door and subclass ElevatorDoor.
2003 Prentice Hall, Inc. All rights reserved.
88
2
Light
Turns
on/off
1
1
ElevatorShaft
1
Resets
Floor
1
2
2
Door
- open : Boolean = false
Button
Signals
arrival
+ openDoor( ) : void
+ closeDoor( ) : void
0..*
- pressed : Boolean = false
1
+ resetButton( ) : void
+ pressButton( ) : void
Presse
1
s
Person
1
1
1
Opens/Closes
1
1
1
Opens
Signals to
move
1
Elevator
ElevatorDoor
Closes
1
1
1
Rings
1
2
Occupies
Resets
Location
- locationName : String
- capacity : Integer = 1 {frozen}
1
# setLocationName( String ) : void
+ getLocationName( ) : String
+ getCapacity( ) : Integer
+ getButton( ) : Button
+ getDoor( ) : Door
Bell
Fig. 10.28 Class diagram of our simulator (incorporating inheritance).
2003 Prentice Hall, Inc. All rights reserved.
89
Location
- locationName : String
- capacity : Integer = 1 {frozen}
# setLocationName( String ) : void
+ getLocationName( ) : String
+ getCapacity( ) : Integer
+ getButton( ) : Button
+ getDoor( ) : Door
Light
- lightOn : Boolean = false
+ turnOnLight( ) : void
+ turnOffLight( ) : void
ElevatorShaft
Person
- ID : Integer
- moving : Boolean = true
- location : Location
+ doorOpened( ) : void
Floor
+ getButton( ) : Button
+ getDoor( ) : Door
Elevator
- moving : Boolean = false
- summoned : Boolean = false
- currentFloor : Location
- destinationFloor : Location
- travelTime : Integer = 5
+ ride( ) : void
+ requestElevator( ) : void
+ enterElevator( ) : void
+ exitElevator( ) : void
+ departElevator( ) : void
+ getButton( ) : Button
+ getDoor( ) : Door
Door
Bell
+ ringBell( ) : void
Button
- pressed : Boolean = false
+ resetButton( ) : void
+ pressButton( ) : void
ElevatorDoor
- open : Boolean = false
+ openDoor( ) : void
+ closeDoor( ) : void
+ openDoor( ) : void
+ closeDoor( ) : void
Fig. 10.29 Class diagram with attributes and operations (incorporating inheritance).
2003 Prentice Hall, Inc. All rights reserved.
90
10.11 Thinking About Objects (cont.)
• Implementation: Forward Engineering
(Incorporating Inheritance)
– Transform design (i.e., class diagram) to code
– Generate “skeleton code” with our design
• Use class Elevator as example
• Two steps (incorporating inheritance)
2003 Prentice Hall, Inc. All rights reserved.
91
10.11 Thinking About Objects (cont.)
public class Elevator extends Location {
// constructor
public Elevator() {}
}
2003 Prentice Hall, Inc. All rights reserved.
92
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Elevator.java
// Generated using class diagrams 10.28 and 10.29
public class Elevator extends Location {
Outline
Elevator.java
// attributes
private boolean moving;
private boolean summoned;
private Location currentFloor;
private Location destinationFloor;
private int travelTime = 5;
private Button elevatorButton;
private Door elevatorDoor;
private Bell bell;
// constructor
public Elevator() {}
// operations
public void ride() {}
public void requestElevator() {}
public void enterElevator() {}
public void exitElevator() {}
public void departElevator() {}
2003 Prentice Hall, Inc.
All rights reserved.
93
25
26
27
28
29
30
31
32
33
34
35
36
// method overriding getButton
public Button getButton()
{
return elevatorButton;
}
Outline
Elevator.java
// method overriding getDoor
public Door getDoor()
{
return elevatorDoor;
}
}
2003 Prentice Hall, Inc.
All rights reserved.
10.12 (Optional) Discovering Design
Patterns: Introducing Creational, Structural
and Behavioral Design Patterns
• Three categories
– Creational
– Structural
– Behavioral
2003 Prentice Hall, Inc. All rights reserved.
94
95
10.12 Discovering Design Patterns (cont.)
• We also introduce
– Concurrent design patterns
• Used in multithreaded systems
• Section 16.12
– Architectural patterns
• Specify how subsystems interact with each other
• Section 18.12
2003 Prentice Hall, Inc. All rights reserved.
96
Section
10.12
14.14
Creational design
patterns
Singleton
Factory Method
Structural design
patterns
Proxy
Adapter, Bridge,
Composite
Behavioral design
patterns
Memento, State
Chain of
Responsibility,
Command,
Observer,
Strategy,
Template Method
18.12
Abstract Factory Decorator, Facade
22.12
Prototype
Iterator
Fig. 10.31
18 Gang of Four design patterns discussed in Java
How to Program 5/e.
2003 Prentice Hall, Inc. All rights reserved.
97
Section
Concurrent design
Architectural patterns
patterns
16.12
Single-Threaded Execution,
Guarded Suspension,
Balking, Read/Write Lock,
Two-Phase Termination
18.12
Model-View-Controller,
Layers
Fig. 10.32
Concurrent design patterns and architectural
patterns discussed in Java How to Program, 5/e.
2003 Prentice Hall, Inc. All rights reserved.
98
10.12 Discovering Design Patterns (cont.)
• Creational design patterns
– Address issues related to object creation
• e.g., prevent from creating more than one object of class
• e.g., defer at run time what type of objects to be created
– Consider 3D drawing program
• User can create cylinders, spheres, cubes, etc.
• At compile time, program does not know what shapes the user
will draw
• Based on user input, program should determine this at run time
2003 Prentice Hall, Inc. All rights reserved.
99
10.12 Discovering Design Patterns (cont.)
• 5 creational design patterns
–
–
–
–
–
Abstract Factory
Builder
Factory Method
Prototype
Singleton
2003 Prentice Hall, Inc. All rights reserved.
(Section 18.12)
(not discussed)
(Section 14.14)
(Section 22.12)
(Section 10.12)
100
10.12 Discovering Design Patterns (cont.)
• Singleton
– Used when system should contain exactly one object of class
• e.g., one object manages database connections
– Ensures system instantiates maximum of one class object
2003 Prentice Hall, Inc. All rights reserved.
101
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Singleton.java
// Demonstrates Singleton design pattern
public final class Singleton {
Outline
Singleton.java
// Singleton object to be returned by getSingletonInstance
private static final Singleton singleton = new Singleton();
// private constructor
private Singleton()
{
System.err.println(
}
Line 10
private constructor
private constructor ensures
ensures only class
class Singleton can
prevents instantiation only
by clients
Singleton can
instantiate Singleton object
instantiate
Singleton object
"Singleton object created." );
// return static Singleton object
public static Singleton getInstance()
{
return singleton;
}
}
2003 Prentice Hall, Inc.
All rights reserved.
102
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Outline
// SingletonTest.java
// Attempt to create two Singleton objects
SingletonExampl
e.java
public class SingletonTest {
// run SingletonExample
public static void main( String args[] )
{
Singleton firstSingleton;
Create
Singleton secondSingleton;
Singleton objects
// create Singleton objects
firstSingleton = Singleton.getInstance();
secondSingleton = Singleton.getInstance();
Lines 13-14
Create Singleton
objects
Line 17
same Singleton
Same Singleton
// the "two" Singletons should refer to same Singleton
if ( firstSingleton == secondSingleton )
System.err.println( "firstSingleton and secondSingleton " +
"refer to the same Singleton object" );
}
}
Singleton object created.
firstSingleton and secondSingleton refer to the same Singleton object
2003 Prentice Hall, Inc.
All rights reserved.
103
10.12 Discovering Design Patterns (cont.)
• Structural design patterns
– Describe common ways to organize classes and objects
–
–
–
–
–
–
–
Adapter
Bridge
Composite
Decorator
Facade
Flyweight
Proxy
2003 Prentice Hall, Inc. All rights reserved.
(Section 14.14)
(Section 14.14)
(Section 14.14)
(Section 18.12)
(Section 18.12)
(not discussed)
(Section 10.12)
104
10.12 Discovering Design Patterns (cont.)
• Proxy
– Allows system to use one object instead of another
• If original object cannot be used (for whatever reason)
– Consider loading several large images in Java applet
• Ideally, we want to see these image instantaneously
• Loading these images can take time to complete
• Applet can use gauge object that informs use of load status
– Gauge object is called the proxy object
• Remove proxy object when images have finished loading
2003 Prentice Hall, Inc. All rights reserved.
105
10.12 Discovering Design Patterns (cont.)
• Behavioral design patterns
– Model how objects collaborate with one another
– Assign responsibilities to algorithms
2003 Prentice Hall, Inc. All rights reserved.
106
10.12 Discovering Design Patterns (cont.)
• Behavioral design patterns
–
–
–
–
–
–
–
–
–
–
–
Chain-of-Responsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer
State
Strategy
Template Method
Visitor
2003 Prentice Hall, Inc. All rights reserved.
(Section 14.14)
(Section 14.14)
(not discussed)
(Section 22.12)
(not discussed)
(Section 10.12)
(Section 14.14)
(Section 10.12)
(Section 14.14)
(Section 14.14)
(not discussed)
107
10.12 Discovering Design Patterns (cont.)
• Memento
– Allows object to save its state (set of attribute values)
– Consider painting program for creating graphics
• Offer “undo” feature if user makes mistake
– Returns program to previous state (before error)
• History lists previous program states
– Originator object occupies state
• e.g., drawing area
– Memento object stores copy of originator object’s attributes
• e.g., memento saves state of drawing area
– Caretaker object (history) contains references to mementos
• e.g., history lists mementos from which user can select
2003 Prentice Hall, Inc. All rights reserved.
108
10.12 Discovering Design Patterns (cont.)
• State
– Encapsulates object’s state
– Consider optional elevator-simulation case study
• Person walks on floor toward elevator
– Use integer to represent floor on which person walks
• Person rides elevator to other floor
• On what floor is the person when riding elevator?
2003 Prentice Hall, Inc. All rights reserved.
109
10.12 Discovering Design Patterns (cont.)
• State
– We implement a solution:
• Abstract superclass Location
• Classes Floor and Elevator extend Location
• Encapsulates information about person location
– Each location has reference to Button and Door
• Class Person contains Location reference
– Reference Floor when on floor
– Reference Elevator when in elevator
2003 Prentice Hall, Inc. All rights reserved.