Chapter 9 - Object-Oriented Programming

Download Report

Transcript Chapter 9 - Object-Oriented Programming

Chapter 9 - Object-Oriented Programming
Outline
9.1
9.2
9.3
9.4
9.5
9.6
9.7
9.8
9.9
9.10
9.11
9.12
9.13
Introduction
Superclasses and Subclasses
protected Members
Relationship between Superclass Objects and Subclass
Objects
Constructors and Finalizers in Subclasses
Implicit Subclass-Object-to-Superclass-Object Conversion
Software Engineering with Inheritance
Composition vs. Inheritance
Case Study: Point, Circle, Cylinder
Introduction to Polymorphism
Type Fields and switch Statements
Dynamic Method Binding
final Methods and Classes
 2002 Prentice Hall. All rights reserved.
Chapter 9 - Object-Oriented Programming
9.14
9.15
9.16
9.17
9.18
9.19
9.20
9.21
9.22
9.23
9.24
Abstract Superclasses and Concrete Classes
Polymorphism Examples
Case Study: A Payroll System Using Polymorphism
New Classes and Dynamic Binding
Case Study: Inheriting Interface and Implementation
Case Study: Creating and Using Interfaces
Inner Class Definitions
Notes on Inner Class Definitions
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
 2002 Prentice Hall. All rights reserved.
9.1 Introduction
• Object-oriented programming
– Inheritance
• Software reusability
• Classes are created from existing ones
– Absorbing attributes and behaviors
– Adding new capabilities
– Convertible inherits from Automobile
– Polymorphism
• Enables developers to write programs in general fashion
– Handle variety of existing and yet-to-be-specified classes
• Helps add new capabilities to system
 2002 Prentice Hall. All rights reserved.
9.1 Introduction (cont.)
• Object-oriented programming
– Inheritance
• Subclass inherits from superclass
– Subclass usually adds instance variables and methods
• Single vs. multiple inheritance
– Java does not support multiple inheritance
• Interfaces (discussed later) achieve the same effect
• “Is a” relationship
– Composition
• “Has a” relationship
 2002 Prentice Hall. All rights reserved.
9.2 Superclasses and Subclasses
• “Is a” Relationship
– Object “is an” object of another class
• Rectangle “is a” quadrilateral
– Class Rectangle inherits from class Quadrilateral
– Form tree-like hierarchical structures
 2002 Prentice Hall. All rights reserved.
Sup e rc la ss
Sub c la sse s
Student
GraduateStudent
UndergraduateStudent
Shape
Circle
Triangle
Rectangle
CarLoan
HomeImprovementLoan
MortgageLoan
FacultyMember
StaffMember
CheckingAccount
SavingsAccount
Loan
Employee
Account
Fig. 9.1
Some simp le inherita nc e exa mp les in w hic h the sub c la ss “ is a ” sup erc la ss.
 2002 Prentice Hall. All rights reserved.
Fig. 9.2 An inheritance hierarchy for university CommunityMembers.
CommunityMember is a direct
superclass of Employee
CommunityMember
CommunityMember is
an indirect superclass of
Faculty
Employee
Faculty
Administrator
 2002 Prentice Hall. All rights reserved.
Student
Staff
Teacher
Alumni
Fig. 9.3 A portion of a Shape class hierarchy.
Shape
TwoDimensionalShape
Circle
Square
 2002 Prentice Hall. All rights reserved.
Triangle
ThreeDimensionalShape
Sphere
Cube
Tetrahedron
9.3
protected Members
• protected access members
– Between public and private in protection
– Accessed only by
• Superclass methods
• Subclass methods
• Methods of classes in same package
– package access
 2002 Prentice Hall. All rights reserved.
9.4 Relationship between Superclass
Objects and Subclass Objects
• Subclass object
– Can be treated as superclass object
• Reverse is not true
– Shape is not always a Circle
– Every class implicitly extends java.lang.Object
• Unless specified otherwise in class definition’s first line
 2002 Prentice Hall. 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
31
32
33
// Fig. 9.4: Point.java
// Definition of class Point
public class Point {
protected int x, y; // coordinates
Outline
protected members prevent
clients from direct access (unless
of
Point
clients
are Point subclasses or
are in same package)
// No-argument constructor
public Point()
{
// implicit call to superclass constructor occurs here
setPoint( 0, 0 );
}
// constructor
public Point( int xCoordinate, int yCoordinate )
{
// implicit call to superclass constructor occurs here
setPoint( xCoordinate, yCoordinate );
}
// set
public
{
x =
y =
}
Point.java
Line 5
protected members
prevent clients from
direct access (unless
clients are Point
subclasses or are in
same package)
x and y coordinates of Point
void setPoint( int xCoordinate, int yCoordinate )
xCoordinate;
yCoordinate;
// get x coordinate
public int getX()
{
return x;
}
 2002 Prentice Hall.
All rights reserved.
34
35
36
37
38
39
40
41
42
43
44
45
46
// get y coordinate
public int getY()
{
return y;
}
Outline
Point.java
// convert into a String representation
public String toString()
{
return "[" + x + ", " + y + "]";
}
}
// end class Point
 2002 Prentice Hall.
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. 9.5: Circle.java
// Definition of class Circle
public class Circle extends Point {
protected double radius;
Circle is a Point subclass
// inherits from Point
Outline
Circle.java
Circle inherits Point’s
// no-argument constructor
protected variables and public
public Circle()
{
methods (except for constuctor)
// implicit call to superclass constructor occurs here
setRadius( 0 );
}
Line 4
Circle is a Point
subclass
Line 4
Implicit call to Point constructor
Circle inherits
// constructor
public Circle( double circleRadius, int xCoordinate,
Point’s protected
int yCoordinate )
variables and public
{
// call superclass constructor to set coordinates
methods (except for
super( xCoordinate, yCoordinate );
constuctor)
// set radius
setRadius( circleRadius );
}
Explicit call to Point
constructor using super
// set radius of Circle
public void setRadius( double circleRadius )
{
radius = ( circleRadius >= 0.0 ? circleRadius : 0.0 );
}
Line 10
Implicit call to Point
constructor
Line 19
Explicit call to Point
constructor using
super
 2002 Prentice Hall.
All rights reserved.
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
Outline
// get radius of Circle
public double getRadius()
{
return radius;
}
// calculate area of Circle
public double area()
{
return Math.PI * radius * radius;
}
Circle.java
Lines 44-48
Override method
toString of class
Point by using same
Override method toString of class
signature
Point by using same signature
// convert the Circle to a String
public String toString()
{
return "Center = " + "[" + x + ", " + y + "]" +
"; Radius = " + radius;
}
}
// end class Circle
 2002 Prentice Hall.
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
31
32
33
34
// Fig. 9.6: InheritanceTest.java
// Demonstrating the "is a" relationship
// Java core packages
import java.text.DecimalFormat;
Outline
InheritanceTest.
java
// Java extension packages
import javax.swing.JOptionPane;
Lines 18-19
public class InheritanceTest {
Instantiate objects
Instantiate Point and Circle objects
// test classes Point and Circle
Line 22
public static void main( String args[] )
Circle invokes
{
Point point1, point2;
method toString
Circle circle1, circle2;
Circle invokes its overridden
point1 = new Point( 30, 50 );
Line 26
toString method
circle1 = new Circle( 2.7, 120, 89 );
Superclass object
references subclass
String output = "Point point1: " + point1.toString() +
"\nCircle circle1: " + circle1.toString();
Superclass object can
Line 29
// use "is a" relationship to refer to a Circlereference subclass object
Point invokes
// with a Point reference
Circle’s toString
point2 = circle1;
// assigns Circle to a Point reference
Point still invokes Circle’s
method
output += "\n\nCircle circle1 (via point2 reference): " +
overridden toString method
point2.toString();
Line 33
// use downcasting (casting a superclass reference to a
Downcast Point to
// subclass data type) to assign point2 to circle2
Downcast Point
to Circle
Circle
circle2 = ( Circle ) point2;
 2002 Prentice Hall.
All rights reserved.
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
invokes
output += "\n\nCircle circle1 (viaCircle
circle2):
" + its overridden
circle2.toString();
toString method
DecimalFormat precision2 = new DecimalFormat( "0.00" );
output += "\nArea of c (via circle2): " +
Circle invokes
precision2.format( circle2.area() );
Outline
InheritanceTest.
method
area
java
// attempt to refer to Point object with Circle reference
Line 36
if ( point1 instanceof Circle ) {
Circle invokes its
circle2 = ( Circle ) point1;
Use instanceof to determine
output += "\n\ncast successful";
overridden toString
if Point refers to Circle
}
method
else
output += "\n\npoint1 does not refer to a Circle";
JOptionPane.showMessageDialog( null, output,
"Demonstrating the \"is a\" relationship",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
// end class InheritanceTest
Line
40
If Point refers to
Circle,
Circle invokes
cast Point as Circle
method area
Line 43
Use instanceof to
determine if Point
refers to Circle
Line 44
If Point refers to
Circle, cast Point
as Circle
 2002 Prentice Hall.
All rights reserved.
Fig. 9.6 Assigning subclass references to superclass references
 2002 Prentice Hall. All rights reserved.
9.5 Constructors and Finalizers in
Subclasses
• Superclass constructor
– Initializes superclass instance variables of subclass
– Not inherited by subclass
– Called by subclass
• Implicitly or explicitly with super reference
 2002 Prentice Hall. All rights reserved.
9.5 Constructors and Finalizers in
Subclasses (cont.)
• finalize method
– Garbage collection
– Subclass finalize method
• should invoke superclass finalize method
 2002 Prentice Hall. 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
31
32
33
34
// Fig. 9.7: Point.java
// Definition of class Point
public class Point extends Object {
protected int x, y; // coordinates of the Point
Superclass constructors
// no-argument constructor
public Point()
{
x = 0;
y = 0;
System.out.println( "Point constructor: " + this );
}
// constructor
public Point( int xCoordinate, int yCoordinate )
{
x = xCoordinate;
y = yCoordinate;
System.out.println( "Point constructor: " + this );
}
Outline
Point.java
Lines 7-20
Superclass constructors
Lines 23-26
Superclass finalize
method uses
protected for
subclass access, but not
for other clients
Superclass finalize method uses
protected for subclass access,
but not for other clients
// finalizer
protected void finalize()
{
System.out.println( "Point finalizer: " + this );
}
// convert Point into a String representation
public String toString()
{
return "[" + x + ", " + y + "]";
}
}
// end class Point
 2002 Prentice Hall.
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
31
// Fig. 9.8: Circle.java
// Definition of class Circle
public class Circle extends Point {
protected double radius;
Outline
// inherits from Point
Implicit call to Point constructor Circle.java
// no-argument constructor
public Circle()
{
// implicit call to superclass constructor here
radius = 0;
System.out.println( "Circle constructor: " + this );
}
Line 9
Implicit call to Point
constructor
Line 19
Explicit call to Point
// Constructor
public Circle( double circleRadius, int xCoordinate,
constructor using
int yCoordinate )
super
Explicit call to Point
{
// call superclass constructor
constructor using super
super( xCoordinate, yCoordinate );
Lines 26-30
Override Point’s
radius = circleRadius;
method finalize,
System.out.println( "Circle constructor: " + this );
}
but call it using super
Override Point’s method
// finalizer
finalize, but call it using super
protected void finalize()
{
System.out.println( "Circle finalizer: " + this );
super.finalize(); // call superclass finalize method
}
 2002 Prentice Hall.
All rights reserved.
32
33
34
35
36
37
38
39
// convert the Circle to a String
public String toString()
{
return "Center = " + super.toString() +
"; Radius = " + radius;
}
}
Outline
Circle.java
// end class Circle
 2002 Prentice Hall.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Fig. 9.9: Test.java
// Demonstrate when superclass and subclass
// constructors and finalizers are called.
public class Test {
Outline
Instantiate Circle objects Test.java
// test when constructors and finalizers are called
public static void main( String args[] )
{
Circle circle1, circle2;
circle1 = new Circle( 4.5, 72, 29 );
circle2 = new Circle( 10, 5, 5 );
circle1 = null;
circle2 = null;
// mark for garbage collection
// mark for garbage collection
System.gc();
// call the garbage collector
Lines 10-11
Instantiate Circle
objects
Line 17
Invoke Circle’s
method finalize by
calling System.gc
}
}
// end class Test
Invoke Circle’s method
finalize by calling System.gc
Point constructor: Center = [72, 29]; Radius = 0.0
Circle constructor: Center = [72, 29]; Radius = 4.5
Point constructor: Center = [5, 5]; Radius = 0.0
Circle constructor: Center = [5, 5]; Radius = 10.0
Circle finalizer: Center = [72, 29]; Radius = 4.5
Point finalizer: Center = [72, 29]; Radius = 4.5
Circle finalizer: Center = [5, 5]; Radius = 10.0
Point finalizer: Center = [5, 5]; Radius = 10.0
 2002 Prentice Hall.
All rights reserved.
9.6 Implicit Subclass-Object-toSuperclass-Object Conversion
• Superclass reference and subclass reference
– Implicit conversion
• Subclass reference to superclass reference
– Subclass object “is a” superclass object
– Four ways to mix and match references
• Refer to superclass object with superclass reference
• Refer to subclass object with subclass reference
• Refer to subclass object with superclass reference
– Can refer only to superclass members
• Refer to superclass object with subclass reference
– Syntax error
 2002 Prentice Hall. All rights reserved.
9.7 Software Engineering with Inheritance
• Inheritance
– Create class (subclass) from existing one (superclass)
• Subclass creation does not affect superclass
– New class inherits attributes and behaviors
– Software reuse
 2002 Prentice Hall. All rights reserved.
9.8 Composition vs. Inheritance
• Inheritance
– “Is a” relationship
– Teacher is an Employee
• Composition
– “Has a” relationship
– Employee has a TelephoneNumber
 2002 Prentice Hall. All rights reserved.
9.9
Case Study: Point, Cylinder, Circle
• Consider point, circle, cylinder hierarchy
– Point is superclass
– Circle is Point subclass
– Cylinder is Circle subclass
 2002 Prentice Hall. 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
31
32
33
34
// Fig. 9.10: Point.java
// Definition of class Point
package com.deitel.jhtp4.ch09;
public class Point {
protected int x, y; // coordinates
Outline
protected members prevent
clients from direct access (unless
of
Point
clients
are Point subclasses or
are in same package)
// No-argument constructor
public Point()
{
// implicit call to superclass constructor occurs here
setPoint( 0, 0 );
}
Constructor and overloaded
constructor
// constructor
public Point( int xCoordinate, int yCoordinate )
{
// implicit call to superclass constructor occurs here
setPoint( xCoordinate, yCoordinate );
}
// set
public
{
x =
y =
}
Point.java
Line 6
protected members
prevent clients from
direct access (unless
clients are Point
subclasses or are in
same package)
Lines 9-20
Constructor and
overloaded constructor
x and y coordinates of Point
void setPoint( int xCoordinate, int yCoordinate )
xCoordinate;
yCoordinate;
// get x coordinate
public int getX()
{
return x;
}
 2002 Prentice Hall.
All rights reserved.
35
36
37
38
39
40
41
42
43
44
45
46
47
// get y coordinate
public int getY()
{
return y;
}
Outline
Point.java
// convert into a String representation
public String toString()
{
return "[" + x + ", " + y + "]";
}
}
// end class Point
 2002 Prentice Hall.
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
31
32
33
34
Outline
// Fig. 9.11: Test.java
// Applet to test class Point
// Java extension packages
import javax.swing.JOptionPane;
Test.java
// Deitel packages
import com.deitel.jhtp4.ch09.Point;
Line 15
Instantiate Point
object
public class Test {
Instantiate Point object
// test class Point
public static void main( String args[] )
{
Point point = new Point( 72, 115 );
// get coordinates
String output = "X coordinate is " + point.getX() +
"\nY coordinate is " + point.getY();
// set coordinates
point.setPoint( 10, 10 );
Lines 18-19
Methods getX and
getY read Point’s
protected variables
Methods getX and getY read
Point’s protected variables
// use implicit call to point.toString()
output += "\n\nThe new location of point is " + point;
JOptionPane.showMessageDialog( null, output,
"Demonstrating Class Point",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
// end class Test
 2002 Prentice Hall.
All rights reserved.
Fig. 9.11 Testing class Point
 2002 Prentice Hall. 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
31
// Fig. 9.12: Circle.java
// Definition of class Circle
package com.deitel.jhtp4.ch09;
public class Circle extends Point {
protected double radius;
Outline
Circle is a Point subclass
// inherits from Point
Circle inherits Point’s
// no-argument constructor
protected variables and public
public Circle()
methods (except for constuctor)
{
// implicit call to superclass constructor occurs here
setRadius( 0 );
}
Circle.java
Line 5
Circle is a Point
subclass
Line 5
Circle inherits
Implicit call to Point constructor
Point’s protected
circleRadius, int xCoordinate,
variables and public
methods (except for
constructor to set coordinates
constuctor)
// constructor
public Circle( double
int yCoordinate )
{
// call superclass
super( xCoordinate, yCoordinate );
// set radius
setRadius( circleRadius );
}
Explicit call to Point
constructor using super
// set radius of Circle
public void setRadius( double circleRadius )
{
radius = ( circleRadius >= 0.0 ? circleRadius : 0.0 );
}
Line 11
Implicit call to Point
constructor
Line 20
explicit call to Point
constructor using
super
 2002 Prentice Hall.
All rights reserved.
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// get radius of Circle
public double getRadius()
{
return radius;
}
Outline
Circle.java
// calculate area of Circle
public double area()
{
return Math.PI * radius * radius;
}
// convert the Circle to a String
public String toString()
{
return "Center = " + "[" + x + ", " + y + "]" +
"; Radius = " + radius;
}
}
// end class Circle
 2002 Prentice Hall.
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
31
32
33
34
35
Outline
// Fig. 9.13: Test.java
// Applet to test class Circle
// Java core packages
import java.text.DecimalFormat;
Test.java
// Java extension packages
import javax.swing.JOptionPane;
Line 19
Instantiate Circle
object
// Deitel packages
import com.deitel.jhtp4.ch09.Circle;
Lines 25 and 28
Instantiate Circle object Calls to methods
// test class Circle
getRadius and
public static void main( String args[] )
setRadius read and
{
Calls
to
methods
getRadius
and
manipulate Circle’s
// create a Circle
setRadius readprotected
and manipulate
Circle circle = new Circle( 2.5, 37, 43 );
variables
DecimalFormat precision2 = new DecimalFormat( "0.00"
);
Circle’s protected variables
public class Test {
Lines 23-24 and 29
Calls to methods getX,
getY and setPoint
read and manipulate
Calls to methods getX, getY and
Circle’s inherited
setPoint read and manipulate Circle’s
protected variables
inherited protected variables
// get coordinates and radius
String output = "X coordinate is " + circle.getX() +
"\nY coordinate is " + circle.getY() +
"\nRadius is " + circle.getRadius();
// set coordinates and radius
circle.setRadius( 4.25 );
circle.setPoint( 2, 2 );
// get String representation of Circle and calculate area
output +=
"\n\nThe new location and radius of c are\n" + circle +
"\nArea is " + precision2.format( circle.area() );
 2002 Prentice Hall.
All rights reserved.
36
37
38
39
40
41
42
43
JOptionPane.showMessageDialog( null, output,
"Demonstrating Class Circle",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
Outline
Test.java
}
}
// end class Test
 2002 Prentice Hall.
All rights reserved.
Fig. 9.13 Testing class Circle
 2002 Prentice Hall. 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
31
// Fig. 9.14: Cylinder.java
// Definition of class Cylinder
package com.deitel.jhtp4.ch09;
Cylinder is a Circle subclass
public class Cylinder extends Circle {
protected double height; // height of Cylinder
Cylinder
Outline
Cylinder.java
inherits Point’s and
Circle’s protected Line 5
variables and public methodsCylinder is a
(except for constuctors) Circle subclass
// no-argument constructor
public Cylinder()
{
// implicit call to superclass constructor here
setHeight( 0 );
}
Line 5
Implicit call to Circle constructor
Cylinder inherits
// constructor
Point’s and
public Cylinder( double cylinderHeight, double cylinderRadius,
Circle’s
int xCoordinate, int yCoordinate )
protected variables
{
// call superclass constructor to set coordinates/radius
and public methods
super( cylinderRadius, xCoordinate, yCoordinate );
(except for constuctors)
// set cylinder height
setHeight( cylinderHeight );
}
Explicit call to Circle
constructor using super
// set height of Cylinder
public void setHeight( double cylinderHeight )
{
height = ( cylinderHeight >= 0 ? cylinderHeight : 0 );
}
Line 11
Implicit call to
Circle constructor
Line 20
Explicit call to
Circle constructor
using super
 2002 Prentice Hall.
All rights reserved.
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
// get height of Cylinder
public double getHeight()
{
return height;
}
Outline
Override method area
of class Circle
// calculate area of Cylinder (i.e., surface area)
public double area()
{
return 2 * super.area() +
2 * Math.PI * radius * height;
}
Cylinder.java
Lines 39-43
Override method area
of class Circle
// calculate volume of Cylinder
public double volume()
{
return super.area() * height;
}
// convert the Cylinder to a String
public String toString()
{
return super.toString() + "; Height = " + height;
}
}
// end class Cylinder
 2002 Prentice Hall.
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
31
32
Outline
// Fig. 9.15: Test.java
// Application to test class Cylinder
// Java core packages
import java.text.DecimalFormat;
Test.java
// Java extension packages
import javax.swing.JOptionPane;
Line 19
Instantiate Cylinder
object
// Deitel packages
import com.deitel.jhtp4.ch09.Cylinder;
public class Test {
Instantiate Cylinder object
// test class Cylinder
public static void main( String args[] )
{
// create Cylinder
Cylinder cylinder = new Cylinder( 5.7, 2.5, 12, 23 );
DecimalFormat precision2 = new DecimalFormat( "0.00" );
Lines 23-31
Method calls read and
manipulate
Cylinder’s
protected variables
and inherited
protected variables
// get coordinates, radius and height
String output = "X coordinate is " + cylinder.getX() +
"\nY coordinate is " + cylinder.getY() +
"\nRadius is " + cylinder.getRadius() +
"\nHeight is " + cylinder.getHeight();
// set coordinates, radius and height
cylinder.setHeight( 10 );
cylinder.setRadius( 4.25 );
cylinder.setPoint( 2, 2 );
Method calls read and manipulate
Cylinder’s protected variables
and inherited protected variables
 2002 Prentice Hall.
All rights reserved.
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// get String representation of Cylinder and calculate
// area and volume
output += "\n\nThe new location, radius " +
"and height of cylinder are\n" + cylinder +
"\nArea is " + precision2.format( cylinder.area() ) +
"\nVolume is " + precision2.format( cylinder.volume() );
Outline
Test.java
JOptionPane.showMessageDialog( null, output,
"Demonstrating Class Cylinder",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
// end class Test
 2002 Prentice Hall.
All rights reserved.
Fig. 9.15 Testing class Test
 2002 Prentice Hall. All rights reserved.
9.10 Introduction to Polymorphism
• Polymorphism
– Helps build extensible systems
– Programs generically process objects as superclass objects
• Can add classes to systems easily
– Classes must be part of generically processed hierarchy
 2002 Prentice Hall. All rights reserved.
9.11 Type Fields and Switch Statements
• switch-based system
– Determine appropriate action for object
• Based on object’s type
– Error prone
• Programmer can forget to make appropriate type test
• Adding and deleting switch statements
 2002 Prentice Hall. All rights reserved.
9.12 Dynamic Method Binding
• Dynamic method binding
– Implements polymorphic processing of objects
– Use superclass reference to refer to subclass object
– Program chooses “correct” method in subclass
 2002 Prentice Hall. All rights reserved.
9.12 Dynamic Method Binding (cont.)
• For example,
– Superclass Shape
– Subclasses Circle, Rectangle and Square
– Each class draws itself according to type of class
• Shape has method draw
• Each subclass overrides method draw
• Call method draw of superclass Shape
– Program determines dynamically which subclass draw
method to invoke
 2002 Prentice Hall. All rights reserved.
9.13 final Methods and Classes
• final method
– Cannot be overridden in subclass
• final class
– Cannot be superclass (cannot be extended)
• Class cannot inherit final classes
 2002 Prentice Hall. All rights reserved.
9.14 Abstract Superclasses and Concrete
Classes
• Abstract classes
– Objects cannot be instantiated
– Too generic to define real objects
• TwoDimensionalShape
– Provides superclass from which other classes may inherit
• Normally referred to as abstract superclasses
• Concrete classes
– Classes from which objects are instantiated
– Provide specifics for instantiating objects
• Square, Circle and Triangle
 2002 Prentice Hall. All rights reserved.
9.15 Polymorphism Examples
• Video game
– Superclass GamePiece
• Contains method drawYourself
– Subclasses Martian, Venutian, LaserBeam, etc.
• Override method drawYourself
– Martian draws itself with antennae
– LaserBeam draws itself as bright red beam
– This is polymorphism
– Easily extensible
• Suppose we add class Mercurian
– Class Mercurian inherits superclass GamePiece
– Overrides method drawYourself
 2002 Prentice Hall. All rights reserved.
9.16 Case Study: A Payroll System Using
Polymorphism
• Abstract methods and polymorphism
– Abstract superclass Employee
• Method earnings applies to all employees
• Person’s earnings dependent on type of Employee
– Concrete Employee subclasses declared final
• Boss
• CommissionWorker
• PieceWorker
• HourlyWorker
 2002 Prentice Hall. 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
31
// Fig. 9.16: Employee.java
// Abstract base class Employee.
abstract class cannot be instantiated
public abstract class Employee {
private String firstName;
private String lastName;
// constructor
public Employee( String first,
{
firstName = first;
lastName = last;
}
Outline
Employee.java
abstract class can have instance data
and nonabstract methods for subclasses
Line 4
abstract class
String last )
cannot be instantiated
abstract class can have constructors for
Lines 5-6 and 16-30
subclasses to initialize inherited dataabstract class can
// get first name
public String getFirstName()
{
return firstName;
}
have instance data and
nonabstract
methods for subclasses
// get last name
public String getLastName()
{
return lastName;
}
Lines 9-13
abstract class can
have constructors for
subclasses to initialize
inherited data
public String toString()
{
return firstName + ' ' + lastName;
}
 2002 Prentice Hall.
All rights reserved.
32
33
34
35
36
37
// Abstract method that must be implemented for each
// derived class of Employee from which objects
// are instantiated.
public abstract double earnings();
}
Outline
Employee.java
// end class Employee
Subclasses must implement
abstract method
Line 35
Subclasses must
implement abstract
method
 2002 Prentice Hall.
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
31
32
// Fig. 9.17: Boss.java
// Boss class derived from Employee.
Boss is an Employee subclass
Outline
public final class Boss extends Employee {
private double weeklySalary;
// constructor for class Boss
public Boss( String first, String
{
super( first, last ); // call
setWeeklySalary( salary );
}
// set Boss's salary
public void setWeeklySalary(
{
weeklySalary = ( salary >
}
// get Boss's pay
public double earnings()
{
return weeklySalary;
}
Boss.java
Boss inherits Employee’s public
methods (except for constuctor)
Line 4
last, double salary )
Boss is an Employee
superclass constructor
subclass
Explicit call to Employee
constructor using super
Line 4
Boss inherits
double salary )
Employee’s public
methods (except for
0 ? salary : 0 );
constuctor)
Required to implement Employee’s
method earnings (polymorphism)
Line 10
Explicit call to
Employee constructor
using super
// get String representation of Boss's name
public String toString()
{
return "Boss: " + super.toString();
}
}
// end class Boss
Lines 21-24
Required to implement
Employee’s method
earnings
(polymorphism)
 2002 Prentice Hall.
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
CommissionWorker is
// Fig. 9.18: CommissionWorker.java
// CommissionWorker class derived from Employee
Employee subclass
an
public final class CommissionWorker extends Employee {
private double salary;
// base salary per week
private double commission; // amount per item sold
private int quantity;
// total items sold for week
// constructor for class CommissionWorker
public CommissionWorker( String first, String last,
double salary, double commission, int quantity )
{
super( first, last ); // call superclass constructor
setSalary( salary );
Explicit call to Employee
setCommission( commission );
constructor using super
setQuantity( quantity );
}
// set CommissionWorker's weekly base salary
public void setSalary( double weeklySalary )
{
salary = ( weeklySalary > 0 ? weeklySalary : 0 );
}
Outline
CommissionWorker
.java
Line 4
CommissionWorker
is an Employee
subclass
Line 13
Explicit call to
Employee constructor
using super
// set CommissionWorker's commission
public void setCommission( double itemCommission )
{
commission = ( itemCommission > 0 ? itemCommission : 0 );
}
 2002 Prentice Hall.
All rights reserved.
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// set CommissionWorker's quantity sold
public void setQuantity( int totalSold
Required to) implement Employee’s
{
method earnings; this implementation
quantity = ( totalSold > 0 ? totalSold : 0 );
differs from that in Boss
}
// determine CommissionWorker's earnings
public double earnings()
{
return salary + commission * quantity;
}
// get String representation of CommissionWorker's name
public String toString()
{
return "Commission worker: " + super.toString();
}
}
Outline
CommissionWorker
.java
Lines 38-41
Required to implement
Employee’s method
earnings; this
implementation differs
from that in Boss
// end class CommissionWorker
 2002 Prentice Hall.
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
31
32
33
34
PieceWorker is an
// Fig. 9.19: PieceWorker.java
// PieceWorker class derived from Employee
Employee subclass
public final class PieceWorker extends Employee {
private double wagePerPiece; // wage per piece output
private int quantity;
// output for week
// constructor for class PieceWorker
public PieceWorker( String first, String last,
double wage, int numberOfItems )
{
super( first, last ); // call superclass constructor
setWage( wage );
Explicit call to Employee
setQuantity( numberOfItems);
constructor using super
}
// set PieceWorker's wage
public void setWage( double wage )
{
wagePerPiece = ( wage > 0 ? wage : 0 );
}
// set number of items output
public void setQuantity( int numberOfItems )
{
quantity = ( numberOfItems > 0 ? numberOfItems : 0 );
}
// determine PieceWorker's earnings
public double earnings()
{
return quantity * wagePerPiece;
}
Outline
PieceWorker.java
Line 4
PieceWorker is an
Employee subclass
Line 12
Explicit call to
Employee constructor
using super
Lines 30-33
Implementation of
Employee’s method
earnings; differs
from that of Boss and
CommissionWorker
Implementation of Employee’s method
earnings; differs from that of Boss
and CommissionWorker
 2002 Prentice Hall.
All rights reserved.
35
36
37
38
39
40
public String toString()
{
return "Piece worker: " + super.toString();
}
}
Outline
PieceWorker.java
// end class PieceWorker
 2002 Prentice Hall.
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
31
32
// Fig. 9.20: HourlyWorker.java
// Definition of class HourlyWorker
HourlyWorker is an
Employee subclass
public final class HourlyWorker extends Employee {
private double wage;
// wage per hour
private double hours; // hours worked for week
// constructor for class HourlyWorker
public HourlyWorker( String first, String last,
double wagePerHour, double hoursWorked )
{
super( first, last );
// call superclass constructor
setWage( wagePerHour );
Explicit call to Employee
setHours( hoursWorked );
}
constructor using super
// Set the wage
public void setWage( double wagePerHour )
{
wage = ( wagePerHour > 0 ? wagePerHour : 0 );
}
// Set the hours worked
public void setHours( double hoursWorked )
{
hours = ( hoursWorked >= 0 && hoursWorked
hoursWorked : 0 );
}
Outline
HourlyWorker.jav
a
Line 4
PieceWorker is an
Employee subclass
Line 12
Explicit call to
Employee constructor
using super
Line 31
Implementation of Employee’s
methodof
Implementation
earnings; differs from
that of other
Employee’s
method
Employee subclasses
earnings; differs
< 168 ?
from that of other
Employee subclasses
// Get the HourlyWorker's pay
public double earnings() { return wage * hours; }
 2002 Prentice Hall.
All rights reserved.
33
34
35
36
37
38
public String toString()
{
return "Hourly worker: " + super.toString();
}
}
// end class HourlyWorker
Outline
HourlyWorker.jav
a
 2002 Prentice Hall.
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
31
Outline
// Fig. 9.21: Test.java
// Driver for Employee hierarchy
// Java core packages
import java.text.DecimalFormat;
// Java extension packages
import javax.swing.JOptionPane;
public class Test {
Test.java
Line 15
Test cannot instantiate Employee Test cannot
but can reference one
instantiate Employee
but can reference one
// test Employee hierarchy
public static void main( String args[] )
{
Employee employee; // superclass reference
String output = "";
Boss boss = new Boss( "John", "Smith", 800.0 );
Instantiate one instance
each of
Lines 18-28
EmployeeInstantiate
subclassesone instance
each of Employee
subclasses
CommissionWorker commisionWorker =
new CommissionWorker(
"Sue", "Jones", 400.0, 3.0, 150 );
PieceWorker pieceWorker =
new PieceWorker( "Bob", "Lewis", 2.5, 200 );
HourlyWorker hourlyWorker =
new HourlyWorker( "Karen", "Price", 13.75, 40 );
DecimalFormat precision2 = new DecimalFormat( "0.00" );
 2002 Prentice Hall.
All rights reserved.
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
// Employee reference to a Boss
employee = boss;
Use Employee to reference Boss
output += employee.toString() + " earned $" +
precision2.format( employee.earnings() ) + "\n" +
boss.toString() + " earned $" +
precision2.format( boss.earnings() ) + "\n"; Method
// Employee reference to a CommissionWorker
employee = commissionWorker;
Outline
Test.java
employee.earnings
Line 33
dynamically binds
to Employee
method
Use
to
boss.earnings
reference Boss
output += employee.toString() + " earned $" +
precision2.format( employee.earnings() ) + "\n" +
commissionWorker.toString() + " earned $" +
precision2.format(
commissionWorker.earnings() ) + "\n";
// Employee reference to a PieceWorker
employee = pieceWorker;
Line 36
Method
employee.earning
s dynamically binds to
Do same for CommissionWorker
method
and PieceWorker
boss.earnings
output += employee.toString() + " earned $" +
precision2.format( employee.earnings() ) + "\n" +
pieceWorker.toString() + " earned $" +
precision2.format( pieceWorker.earnings() ) + "\n";
Lines 41-55
Do same for
CommissionWorker
and PieceWorker
 2002 Prentice Hall.
All rights reserved.
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
Outline
// Employee reference to an HourlyWorker
employee = hourlyWorker;
output += employee.toString() + " earned $" +
precision2.format( employee.earnings() ) + "\n" +
hourlyWorker.toString() + " earned $" +
precision2.format( hourlyWorker.earnings() ) + "\n";
JOptionPane.showMessageDialog( null, output,
"Demonstrating Polymorphism",
JOptionPane.INFORMATION_MESSAGE );
Test.java
Lines 58-63
Repeat for
HourlyWorker
Repeat for HourlyWorker
System.exit( 0 );
}
}
// end class Test
 2002 Prentice Hall.
All rights reserved.
9.17 New Classes and Dynamic Binding
• Dynamic binding (late binding)
– Object’s type need not be know at compile time
– At run time, call is matched with method of called object
 2002 Prentice Hall. All rights reserved.
9.18 Case Study: Inheriting Interface and
Implementation
• Point, Circle, Cylinder hierarchy
– Modify by including abstract superclass Shape
• Demonstrates polymorphism
• Contains abstract method getName
– Each subclass must implement method getName
• Contains (nonabstract) methods area and volume
– Return 0 by default
– Each subclass overrides these methods
 2002 Prentice Hall. 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
// Fig. 9.22: Shape.java
Shape
// Definition of abstract base class Shape
cannot be instantiated
public abstract class Shape extends Object {
// return shape's area
public double area()
{
return 0.0;
}
// return shape's volume
public double volume()
{
return 0.0;
}
Shape.java
Line 4
Shape cannot be
instantiated
abstract class can
have nonabstract
methods for subclasses
// abstract method must be defined by concrete subclasses
// to return appropriate shape name
public abstract String getName();
}
Outline
// end class Shape
Concrete subclasses must
implement method getName
Lines 7-16
abstract class can
have nonabstract
methods for subclasses
Line 20
Concrete subclasses
must implement
method getName
 2002 Prentice Hall.
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
31
// Fig. 9.23: Point.java
// Definition of class Point
Point inherits Shape’s
public methods
public class Point extends Shape {
protected int x, y; // coordinates of the Point
// no-argument constructor
public Point()
{
setPoint( 0, 0 );
}
protected members prevent
clients from direct access (unless
clients are Point subclasses or
are in same package)
// constructor
public Point( int xCoordinate, int yCoordinate )
{
setPoint( xCoordinate, yCoordinate );
}
// set
public
{
x =
y =
}
x and y coordinates of Point
void setPoint( int xCoordinate, int yCoordinate )
xCoordinate;
yCoordinate;
Outline
Point.java
Line 4
Point inherits
Shape’s public
methods
Line 5
protected members
prevent clients from
direct access (unless
clients are Point
subclasses or are in
same package)
// get x coordinate
public int getX()
{
return x;
}
 2002 Prentice Hall.
All rights reserved.
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
Point.java
// convert point into String representation
public String toString()
{
return "[" + x + ", " + y + "]";
}
Implementation
Lines 45-48
Implementation of
Shape’s method
getName
// return shape name
public String getName()
{
return "Point";
}
}
Outline
// get y coordinate
public int getY()
{
return y;
}
// end class Point
of Shape’s
method getName
*** Note ***
Point does not override methods
area and volume, because points
have neither area nor volume
 2002 Prentice Hall.
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
31
32
33
34
35
// Fig. 9.24: Circle.java
// Definition of class Circle
public class Circle extends Point {
protected double radius;
Circle inherits variables/methods
from Point and Shape
// inherits from Point
// no-argument constructor
public Circle()
{
// implicit call to superclass constructor here
setRadius( 0 );
}
Outline
Circle.java
Line 4
Circle inherits
variables/methods from
Point and Shape
Lines 5 and 24-34
Methods for
reading/setting
protected value
for reading/setting
protected value
// constructor
public Circle( double circleRadius, int xCoordinate,
int yCoordinate )
{
// call superclass constructor
Methods
super( xCoordinate, yCoordinate );
setRadius( circleRadius );
}
// set radius of Circle
public void setRadius( double circleRadius )
{
radius = ( circleRadius >= 0 ? circleRadius : 0 );
}
// get radius of Circle
public double getRadius()
{
return radius;
}
 2002 Prentice Hall.
All rights reserved.
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// calculate area of Circle
public double area()
{
return Math.PI * radius * radius;
}
Outline
Circle.java
Override method area but not method volume
// convert Circle to a String represention
(circles do not have volume)
Lines 37-40
public String toString()
Override method area
{
return "Center = " + super.toString() +
but not method
"; Radius = " + radius;
volume (circles do not
}
Implementation of Shape’s
have volume)
method getName
// return shape name
public String getName()
{
return "Circle";
}
}
// end class Circle
Lines 50-53
Implementation of
Shape’s method
getName
 2002 Prentice Hall.
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. 9.25: Cylinder.java
// Definition of class Cylinder.
Cylinder inherits variables
and methods from Point,
Circle and Shape
public class Cylinder extends Circle {
protected double height; // height of Cylinder
// no-argument constructor
public Cylinder()
{
// implicit call to superclass constructor here
setHeight( 0 );
}
Outline
Cylinder.java
Line 4
Cylinder inherits
variables and methods
from Point, Circle
and Shape
// constructor
public Cylinder( double cylinderHeight,
double cylinderRadius, int xCoordinate,
int yCoordinate )
{
// call superclass constructor
super( cylinderRadius, xCoordinate, yCoordinate );
setHeight( cylinderHeight );
}
// set height of Cylinder
public void setHeight( double cylinderHeight )
{
height = ( cylinderHeight >= 0 ? cylinderHeight : 0 );
}
 2002 Prentice Hall.
All rights reserved.
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
59
60
61
Outline
// get height of Cylinder
public double getHeight()
{
return height;
}
Cylinder.java
// calculate area of Cylinder (i.e., surface area)
public double area()
{
return 2 * super.area() + 2 * Math.PI * radius * height;
}
// calculate volume of Cylinder
public double volume()
{
return super.area() * height;
}
Override methods area
and volume
Lines 38-47
Override methods
area and volume
Lines 56-59
Implementation of
Shape’s method
getName
// convert Cylinder to a String representation
public String toString()
{
return super.toString() + "; Height = " + height;
}
// return shape name
public String getName()
{
return "Cylinder";
}
}
Implementation of Shape’s
method getName
// end class Cylinder
 2002 Prentice Hall.
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
31
Outline
// Fig. 9.26: Test.java
// Class to test Shape, Point, Circle, Cylinder hierarchy
// Java core packages
import java.text.DecimalFormat;
// Java extension packages
import javax.swing.JOptionPane;
public class Test {
Test.java
Instantiate one instance
each of Shape subclasses
// test Shape hierarchy
public static void main( String args[] )
{
// create shapes
Point point = new Point( 7, 11 );
Circle circle = new Circle( 3.5, 22, 8 );
Cylinder cylinder = new Cylinder( 10, 3.3, 10, 10 );
// create Shape array
Shape arrayOfShapes[] = new Shape[ 3 ];
Lines 16-18
Instantiate one instance
each of Shape
subclasses
Lines 21-30
Create three Shapes to
reference each subclass
object
Create three Shapes to
reference each subclass object
// aim arrayOfShapes[ 0 ] at subclass Point object
arrayOfShapes[ 0 ] = point;
// aim arrayOfShapes[ 1 ] at subclass Circle object
arrayOfShapes[ 1 ] = circle;
// aim arrayOfShapes[ 2 ] at subclass Cylinder object
arrayOfShapes[ 2 ] = cylinder;
 2002 Prentice Hall.
All rights reserved.
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
// get name and String representation of each shape
String output =
point.getName() + ": " + point.toString() + "\n" +
circle.getName() + ": " + circle.toString() + "\n" +
cylinder.getName() + ": " + cylinder.toString();
DecimalFormat precision2 = new DecimalFormat( "0.00" );
// loop through arrayOfShapes and get name,
// area and volume of each shape in arrayOfShapes
for ( int i = 0; i < arrayOfShapes.length; i++ ) {
output += "\n\n" + arrayOfShapes[ i ].getName() +
": " + arrayOfShapes[ i ].toString() +
"\nArea = " +
precision2.format( arrayOfShapes[ i ].area() ) +
"\nVolume = " +
precision2.format( arrayOfShapes[ i ].volume() );
}
JOptionPane.showMessageDialog( null, output,
"Demonstrating Polymorphism",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
Outline
Test.java
Dynamically
bind
Line 43
method Dynamically
getName bind
method getName
Dynamically bind method
Line
area
for 46
Circle and
Dynamically
bind
Cylinder objects
method area for
Circle and
Cylinder objects
Dynamically Line
bind method
48
volume for Cylinder
object
Dynamically
bind
method volume for
Cylinder object
// end class Test
 2002 Prentice Hall.
All rights reserved.
Outline
Test.java
 2002 Prentice Hall.
All rights reserved.
9.19 Case Study: Creating and Using
Interfaces
• Use interface Shape
– Replace abstract class Shape
• Interface
– Definition begins with interface keyword
– Classes implement an interface (and its methods)
– Contains public abstract methods
• Classes (that implement the interface) must implement these
methods
 2002 Prentice Hall. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Outline
// Fig. 9.27: Shape.java
// Definition of interface Shape
public interface Shape {
// calculate area
public abstract double area();
// calculate volume
public abstract double volume();
// return shape name
public abstract String getName();
Classes that implement Shape
must implement these methods
Shape.java
Lines 7-13
Classes that
implement Shape
must implement these
methods
}
 2002 Prentice Hall.
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
31
Outline
// Fig. 9.28: Point.java
// Definition of class Point
public class Point extends Object implements Shape {
protected int x, y; // coordinates of the Point
// no-argument constructor
public Point()
{
setPoint( 0, 0 );
}
Point.java
Line 4
Point implements
Point implements interface Shapeinterface Shape
// constructor
public Point( int xCoordinate, int yCoordinate )
{
setPoint( xCoordinate, yCoordinate );
}
// Set
public
{
x =
y =
}
x and y coordinates of Point
void setPoint( int xCoordinate, int yCoordinate )
xCoordinate;
yCoordinate;
// get x coordinate
public int getX()
{
return x;
}
 2002 Prentice Hall.
All rights reserved.
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
59
60
61
62
Outline
// get y coordinate
public int getY()
{
return y;
}
Point.java
// convert point into String representation
public String toString()
{
return "[" + x + ", " + y + "]";
}
Lines 45-60
Implement methods
specified by interface
Shape
// calculate area
public double area()
{
return 0.0;
}
// calculate volume
public double volume()
{
return 0.0;
}
Implement methods specified
by interface Shape
// return shape name
public String getName()
{
return "Point";
}
}
// end class Point
 2002 Prentice Hall.
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
31
32
33
34
35
Outline
// Fig. 9.29: Circle.java
// Definition of class Circle
public class Circle extends Point {
protected double radius;
// inherits from Point
Circle.java
Circle inherits variables/methods
// no-argument constructor
Line 4
public Circle()
from Point, including method
Circle inherits
{
implementations of Shape
// implicit call to superclass constructor here
variables/methods
setRadius( 0 );
Point, including
}
// constructor
public Circle( double circleRadius, int xCoordinate,
int yCoordinate )
{
// call superclass constructor
super( xCoordinate, yCoordinate );
method implementations of Shape
setRadius( circleRadius );
}
// set radius of Circle
public void setRadius( double circleRadius )
{
radius = ( circleRadius >= 0 ? circleRadius : 0 );
}
// get radius of Circle
public double getRadius()
{
return radius;
}
from
 2002 Prentice Hall.
All rights reserved.
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// calculate area of Circle
public double area()
{
return Math.PI * radius * radius;
}
Outline
Override method toString
// convert Circle to a String represention
public String toString()
{
return "Center = " + super.toString() +
"; Radius = " + radius;
}
// return shape name
public String getName()
{
return "Circle";
}
}
Circle.java
Lines 43-47
Override method
toString
Override methods area and
Lines 37-40 and 50-53
getName but not method volume
Override methods
area and getName
but not method
volume
// end class Circle
 2002 Prentice Hall.
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
31
32
33
34
35
// Fig. 9.30: Cylinder.java
// Definition of class Cylinder.
public class Cylinder extends Circle {
protected double height; // height of Cylinder
Circle inherits variables/methods
// no-argument constructor
public Cylinder()
from Point and Circle and
{
method implementations of Shape
// implicit call to superclass constructor here
setHeight( 0 );
}
// constructor
public Cylinder( double cylinderHeight,
double cylinderRadius, int xCoordinate,
int yCoordinate )
{
// call superclass constructor
super( cylinderRadius, xCoordinate, yCoordinate );
Outline
Cylinder.java
Line 4
Circle inherits
variables/methods from
Point and Circle
and method
implementations of
Shape
setHeight( cylinderHeight );
}
// set height of Cylinder
public void setHeight( double cylinderHeight )
{
height = ( cylinderHeight >= 0 ? cylinderHeight : 0 );
}
// get height of Cylinder
public double getHeight()
{
return height;
}
 2002 Prentice Hall.
All rights reserved.
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// calculate area of Cylinder (i.e., surface area)
public double area()
{
return 2 * super.area() + 2 * Math.PI * radius * height;
}
// calculate volume of Cylinder
public double volume()
{
return super.area() * height;
}
// convert Cylinder to a String
public String toString()
{
return super.toString() + ";
}
Override method toString
Outline
Cylinder.java
Lines 50-53
Override method
toString
Override methods area,
Line 38-59
volume and getName
representation
Override methods
area, volume and
getName
Height = " + height;
// return shape name
public String getName()
{
return "Cylinder";
}
}
// end class Cylinder
 2002 Prentice Hall.
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
31
// Fig. 9.31: Test.java
// Test Point, Circle, Cylinder hierarchy with interface Shape.
// Java core packages
import java.text.DecimalFormat;
// Java extension packages
import javax.swing.JOptionPane;
Outline
Test.java
Fig. 9.31 is identical
to Fig. 9.26
Fig. 9.31 is identical to
Fig. 9.26
public class Test {
// test Shape hierarchy
public static void main( String args[] )
{
// create shapes
Point point = new Point( 7, 11 );
Circle circle = new Circle( 3.5, 22, 8 );
Cylinder cylinder = new Cylinder( 10, 3.3, 10, 10 );
// create Shape array
Shape arrayOfShapes[] = new Shape[ 3 ];
// aim arrayOfShapes[ 0 ] at subclass Point object
arrayOfShapes[ 0 ] = point;
// aim arrayOfShapes[ 1 ] at subclass Circle object
arrayOfShapes[ 1 ] = circle;
// aim arrayOfShapes[ 2 ] at subclass Cylinder object
arrayOfShapes[ 2 ] = cylinder;
 2002 Prentice Hall.
All rights reserved.
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
// get name and String representation of each shape
String output =
point.getName() + ": " + point.toString() + "\n" +
circle.getName() + ": " + circle.toString() + "\n" +
cylinder.getName() + ": " + cylinder.toString();
Outline
Test.java
DecimalFormat precision2 = new DecimalFormat( "0.00" );
// loop through arrayOfShapes and get name,
// area and volume of each shape in arrayOfShapes
for ( int i = 0; i < arrayOfShapes.length; i++ ) {
output += "\n\n" + arrayOfShapes[ i ].getName() +
": " + arrayOfShapes[ i ].toString() +
"\nArea = " +
precision2.format( arrayOfShapes[ i ].area() ) +
"\nVolume = " +
precision2.format( arrayOfShapes[ i ].volume() );
}
JOptionPane.showMessageDialog( null, output,
"Demonstrating Polymorphism",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
// end class Test
 2002 Prentice Hall.
All rights reserved.
Outline
Test.java
Output is identical to
that of Fig. 9.26
Output is identical to
that of Fig. 9.26
 2002 Prentice Hall.
All rights reserved.
9.20 Inner Class Definitions
• Inner classes
– Class is defined inside another class body
– Frequently used with GUI handling
• Declare ActionListener inner class
• GUI components can register ActionListeners for events
– Button events, key events, etc.
 2002 Prentice Hall. 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
31
32
33
34
35
Outline
// Fig. 9.32: Time.java
// Time class definition.
// Java core packages
import java.text.DecimalFormat;
Time.java
// This class maintains the time in 24-hour format
public class Time extends Object {
private int hour;
// 0 - 23
private int minute;
// 0 - 59
private int second;
// 0 - 59
Line 8
Same Time class used
in Chapter 8
// Time constructor initializes each instance variable
// to zero. Ensures that Time object starts in a
// consistent state.
public Time()
Same Time class
{
setTime( 0, 0, 0 );
used in Chapter 8
}
// Set a new time value using universal time. Perform
// validity checks on the data. Set invalid values to zero.
public void setTime( int hour, int minute, int second )
{
setHour( hour );
setMinute( minute );
setSecond( second );
}
// validate and set hour
public void setHour( int h )
{
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
}
 2002 Prentice Hall.
All rights reserved.
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
Outline
// validate and set minute
public void setMinute( int m )
{
minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
}
Time.java
// validate and set second
public void setSecond( int s )
{
second = ( ( s >= 0 && s < 60 ) ? s : 0 );
}
// get hour
public int getHour()
{
return hour;
}
Mutator and accessor
methods
Mutator and
accessor methods
// get minute
public int getMinute()
{
return minute;
}
// get second
public int getSecond()
{
return second;
}
 2002 Prentice Hall.
All rights reserved.
66
67
68
69
70
71
72
73
74
75
76
77
78
// convert to String in standard-time format
public String toString()
{
DecimalFormat twoDigits = new DecimalFormat( "00" );
return ( ( getHour() == 12 || getHour() == 0 ) ?
12 : getHour() % 12 ) + ":" +
twoDigits.format( getMinute() ) + ":" +
twoDigits.format( getSecond() ) +
( getHour() < 12 ? " AM" : " PM" );
}
}
// end class Time
Outline
Time.java
Lines 67-76
Override method
java.lang.Object
.toString
Override method
java.lang.Object.toString
 2002 Prentice Hall.
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
31
Outline
// Fig. 9.33: TimeTestWindow.java
// Demonstrating the Time class set and get methods
// Java core packages
import java.awt.*;
import java.awt.event.*;
JFrame provides basic window
attributes and behaviors
// Java extension packages
import javax.swing.*;
public class TimeTestWindow extends JFrame {
private Time time;
private JLabel hourLabel, minuteLabel, secondLabel;
private JTextField hourField, minuteField,
secondField, displayField;
JFrame
private JButton exitButton;
TimeTestWindow.j
ava
Line 11
JFrame provides basic
window attributes and
behaviors
(unlike JApplet)
Line 19
has constructor JFrame (unlike
JApplet) has
Instantiate Time object
constructor
// set up GUI
public TimeTestWindow()
{
super( "Inner Class Demonstration" );
Line 23
Instantiate Time object
time = new Time();
// create an instance of inner class ActionEventHandler
ActionEventHandler handler = new ActionEventHandler();
// set up GUI
Container container = getContentPane();
container.setLayout( new FlowLayout() );
Line 26
Instantiate object of
inner-class that
Instantiate object ofimplements
innerclass that implements
ActionListener
ActionListener
 2002 Prentice Hall.
All rights reserved.
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
59
60
61
62
63
64
65
hourLabel = new JLabel( "Set Hour" );
hourField = new JTextField( 10 );
hourField.addActionListener( handler );
container.add( hourLabel );
container.add( hourField );
minuteLabel = new JLabel( "Set minute" );
minuteField = new JTextField( 10 );
minuteField.addActionListener( handler );
container.add( minuteLabel );
container.add( minuteField );
secondLabel = new JLabel( "Set Second" );
secondField = new JTextField( 10 );
secondField.addActionListener( handler );
container.add( secondLabel );
container.add( secondField );
Outline
TimeTestWindow.j
ava
Line 34, 40, 46 and 55
Register ActionEventHandler with
GUI components
Register
ActionEventHandler
with GUI components
displayField = new JTextField( 30 );
displayField.setEditable( false );
container.add( displayField );
exitButton = new JButton( "Exit" );
exitButton.addActionListener( handler );
container.add( exitButton );
}
// end constructor
// display time in displayField
public void displayTime()
{
displayField.setText( "The time is: " + time );
}
 2002 Prentice Hall.
All rights reserved.
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
Outline
// create TimeTestWindow and display it
public static void main( String args[] )
{
TimeTestWindow window = new TimeTestWindow();
}
TimeTestWindow.j
window.setSize( 400, 140 );
Define inner class that implements ava
window.setVisible( true );
ActionListener interface
Lines 77-78
inner class definition for handling JTextField and
Define inner class
//
// JButton events
private class ActionEventHandler
implements ActionListener {
Must implement method actionPerformed
of ActionListener Line 81
Must implement
// method to handle action events
method
public void actionPerformed( ActionEvent event )
actionPerformed
{
// user pressed exitButton
When user
presses JButton or Enter key,
if ( event.getSource() == exitButton
)
Line 81
System.exit( 0 );
// terminate
the actionPerformed
application
method
is invoked
// user pressed Enter key in hourField
else if ( event.getSource() == hourField ) {
time.setHour(
Integer.parseInt( event.getActionCommand() ) );
hourField.setText( "" );
}
Determine
When user presses
button or key, method
actionPerformed
is invoked
actionLines
depending
84-99
on where event Determine
originated action
depending on where
event originated
// user pressed Enter key in minuteField
else if ( event.getSource() == minuteField ) {
time.setMinute(
Integer.parseInt( event.getActionCommand() ) );
minuteField.setText( "" );
}
 2002 Prentice Hall.
All rights reserved.
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// user pressed Enter key in secondField
else if ( event.getSource() == secondField ) {
time.setSecond(
Integer.parseInt( event.getActionCommand() ) );
secondField.setText( "" );
}
Outline
TimeTestWindow.j
ava
displayTime();
}
}
}
// end inner class ActionEventHandler
// end class TimeTestWindow
 2002 Prentice Hall.
All rights reserved.
Outline
TimeTestWindow.j
ava
 2002 Prentice Hall.
All rights reserved.
9.20 Inner Class Definitions (cont.)
• Anonymous inner class
– Inner class without name
– Created when class is defined in program
 2002 Prentice Hall. 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
31
// Fig. 9.34: TimeTestWindow.java
// Demonstrating the Time class set and get methods
// Java core packages
import java.awt.*;
import java.awt.event.*;
Outline
TimeTestWindow.j
ava
// Java extension packages
import javax.swing.*;
public class TimeTestWindow extends JFrame {
private Time time;
private JLabel hourLabel, minuteLabel, secondLabel;
private JTextField hourField, minuteField,
secondField, displayField;
// set up GUI
public TimeTestWindow()
{
super( "Inner Class Demonstration" );
// create Time object
time = new Time();
// create GUI
Container container = getContentPane();
container.setLayout( new FlowLayout() );
hourLabel = new JLabel( "Set Hour" );
hourField = new JTextField( 10 );
 2002 Prentice Hall.
All rights reserved.
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
59
60
61
// register hourField event handler
hourField.addActionListener(
// anonymous inner class
new ActionListener() {
Outline
Define anonymous inner class that
implements ActionListener TimeTestWindow.j
ava
public void actionPerformed( ActionEvent event )
{
Line 36
time.setHour(
Integer.parseInt( event.getActionCommand() ) );
Define anonymous
hourField.setText( "" );
class
Inner class implements inner
method
displayTime();
}
actionPerformed of
}
// end anonymous inner class
); // end call to addActionListener
container.add( hourLabel );
container.add( hourField );
minuteLabel = new JLabel( "Set minute"
minuteField = new JTextField( 10 );
// register minuteField event handler
minuteField.addActionListener(
// anonymous inner class
new ActionListener() {
Lines 38-44
ActionListener
Inner class implements
method
Pass ActionListener
as
actionPerformed
argument to GUI component’s
method addActionListener
Line 33
Pass Action);
Listener to GUI
component’s method
addActionListener
Repeat process for JTextField
Line 57-60
minuteField
Repeat process for
minuteField
 2002 Prentice Hall.
All rights reserved.
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
public void actionPerformed( ActionEvent event )
{
time.setMinute(
Integer.parseInt( event.getActionCommand() ) );
minuteField.setText( "" );
displayTime();
}
Logic differs from logic in
}
Outline
TimeTestWindow.j
ava
actionPerformed method of Line 64-67
hourField’s inner class
Logic differs from logic
to addActionListener
in actionPerformed method
minuteLabel );
of hourField’s inner
minuteField );
class
// end anonymous inner class
); // end call
container.add(
container.add(
secondLabel = new JLabel( "Set Second" );
secondField = new JTextField( 10 );
Line 80-83
Repeat process for JTextField
Repeat process for
secondField
JTextField
secondField
secondField.addActionListener(
// anonymous inner class
new ActionListener() {
public void actionPerformed( ActionEvent event )
{
time.setSecond(
Integer.parseInt( event.getActionCommand() ) );
secondField.setText( "" );
displayTime();
}
Logic differs from logic in
}
Line 87-90
Logic differs from logic
in actionPerformed methods
of other inner classes
actionPerformed methods of
other inner classes
// end anonymous inner class
); // end call to addActionListener
 2002 Prentice Hall.
All rights reserved.
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
Outline
container.add( secondLabel );
container.add( secondField );
displayField = new JTextField( 30 );
displayField.setEditable( false );
container.add( displayField );
TimeTestWindow.j
ava
}
// display time in displayField
public void displayTime()
{
displayField.setText( "The time is: " + time );
}
// create TimeTestWindow, register for its window events
// and display it to begin application's execution
public static void main( String args[] )
{
TimeTestWindow window = new TimeTestWindow();
Define
// register listener for windowClosing event
window.addWindowListener(
Line 118-131
Define anonymous
inner class that extends
WindowsAdapter to
enable closing of
JFrame
anonymous inner class that
extends WindowsAdapter to
enable closing of JFrame
// anonymous inner class for windowClosing event
new WindowAdapter() {
// terminate application when user closes window
public void windowClosing( WindowEvent event )
{
System.exit( 0 );
}
}
// end anonymous inner class
); // end call to addWindowListener
 2002 Prentice Hall.
All rights reserved.
132
133
134
135
136
137
window.setSize( 400, 120 );
window.setVisible( true );
}
}
// end class TimeTestWindow
Outline
TimeTestWindow.j
ava
 2002 Prentice Hall.
All rights reserved.
Outline
TimeTestWindow.j
ava
 2002 Prentice Hall.
All rights reserved.
9.21 Notes on Inner Class Definitions
• Notes for inner-class definition and use
– Compiling class that contains inner class
• Results in separate .class file
– Inner classes with class names
• public, protected, private or package access
– Access outer class’ this reference
OuterClassName.this
– Outer class is responsible for creating inner class objects
– Inner classes can be declared static
 2002 Prentice Hall. All rights reserved.
9.22 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 data types can be processed polymorphically
– Declared as final
– Many methods are declared static
 2002 Prentice Hall. All rights reserved.
9.23 (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
 2002 Prentice Hall. All rights reserved.
9.23 Thinking About Objects (cont.)
• ElevatorButton and FloorButton
–
–
–
–
Treated as separate classes
Both have attribute pressed
Both have behaviors pressButton and resetButton
Move attribute and behaviors into superclass Button?
• We must examine whether these objects have distinct behavior
– If same behavior
• They are objects of class Button
– If different behavior
• They are objects of distinct Button subclasses
 2002 Prentice Hall. All rights reserved.
Fig. 9.35 Attributes and operations of classes FloorButton and ElevatorButton.
FloorButto n
Ele va to rButton
- pressed : Boolea n = fa lse
- pressed : Boolea n = fa lse
+ resetButton( ) : v oid
+ p ressButton( ) : v oid
+ resetButton( ) : v oid
+ p ressButton( ) : v oid
 2002 Prentice Hall. All rights reserved.
9.23 Thinking About Objects (cont.)
• ElevatorButton and FloorButton
– FloorButton requests Elevator to Floor of request
• Elevator will sometimes respond
– ElevatorButton signals Elevator to move
• Elevator will always respond
– Neither button decides for the Elevator to move
• Elevator decides itself
– Both buttons signal Elevator to move
• Therefore, both buttons exhibit identical behavior
– They are objects of class Button
– Combine (not inherit) ElevatorButton and
FloorButton into class Button
 2002 Prentice Hall. All rights reserved.
9.23 Thinking About Objects (cont.)
• ElevatorDoor and FloorDoor
–
–
–
–
Treated as separate classes
Both have attribute open
Both have behaviors openDoor and closeDoor
Both door “inform” a Person that a door has opened
• both doors exhibit identical behavior
– They are objects of class Door
– Combine (not inherit) ElevatorDoor and FloorDoor
into class Door
 2002 Prentice Hall. All rights reserved.
Fig. 9.36 Attributes and operations of classes FloorDoor and ElevatorDoor
FloorDo or
Eleva to rDoor
- ope n : Boolean = fa lse
- ope n : Boolean = fa lse
+ op enDoor( ) : v oid
+ c loseDo or( ) : vo id
+ op enDoor( ) : v oid
+ c loseDo or( ) : vo id
 2002 Prentice Hall. All rights reserved.
9.23 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
 2002 Prentice Hall. All rights reserved.
Fig. 9.37 Class diagram modeling generalization of superclass Location and
subclasses Elevator and Floor.
Pound sign (#) indicates
protected member
Italics indicate abstract
class or method
Loc a tion
- loc atio nNa me : String
- c ap ac ity : Intege r = 1 {froze n}
# setLo c atio nName ( String ) : vo id
+ g etLo c ationNam e( ) : String
+ g etCa pa c ity( ) : Integer
+ g etButton( ) : Butto n
+ g etDoor( ) : Doo r
Italics indicate abstract
class or method
Elev ator
- m oving : Bo olean = false
- sum moned : Boo lea n = false
- c urrentFlo or : Integ er
- d estina tionFloor : Inte ger
- tra velTim e : Intege r = 5
+ ride( ) : v oid
+ req uestEleva to r( ) : void
+ enterElev ator( ) : v oid
+ exitElev ator( ) : v oid
+ dep artEle vator( ) : void
+ getButton( ) : Button
+ getDoo r( ) : Door
 2002 Prentice Hall. All rights reserved.
Outline
Pound sign (#)
{frozen} indicates
indicates protected
constant (final in Java)
member
Flo or
+ g etButto n( ) : Button
+ g etDo or( ) : Door
{frozen} indicates
constant (final in Java)
Concrete classes
implement abstract
Concrete classesmethods
implement
abstract methods
Fig. 9.38 Class diagram of our simulator (incorporating inheritance).
Creates
1
Light
ElevatorModel
2
1
2
Floor
1
Turns
on/off
1
1
1
ElevatorShaft
1
1
2
Doo r
- op en : Boolea n = fa lse
Signals
arrival
+ o penDoo r( ) : vo id
+ c lo seDoor( ) : v oid
Resets
2
Button
- pressed : Boolean = false
+ resetButton( ) : void
+ pressButton( ) : void
1
0..*
Presses
Person
1
1
1
1
1
Opens
Closes
1
Elevator
1
1
Rings
Bell
 2002 Prentice Hall. All rights reserved.
1
Signals to
move
Resets
Occupies
1
Location
- locationName : String
2 - capacity : Integer = 1 {frozen}
# setLocationName( String ) : void
+ getLocationName( ) : String
+ getCapacity( ) : Integer
+ getButton( ) : Button
+ getDoor( ) : Door
1
Fig. 9.39 Class diagram with attributes and operations (incorporating inheritance).
Eleva torM odel
Lig ht
- numb erOfPe ople : Integ er = 0
- lig htOn : Boo lea n = false
+ a dd Pe rson( ) : vo id
+ turnOnLig ht( ) : vo id
+ turnOffLig ht( ) : vo id
Loc a tion
- lo c ationNam e : String
- c ap ac ity : Integ er = 1 {frozen}
# setLoc ationNam e( String ) : v oid
+ getLoc a tionNam e( ) : String
+ getC apa c ity ( ) : Intege r
+ getButton( ) : Button
+ getDoor( ) : Door
Person
- ID : Integ er
- m oving : Bo olean = true
- loc a tion : Lo c ation
Ele va torShaft
Flo or
+ g etButto n( ) : Button
+ g etDo or( ) : Door
Bell
+ doo rOpe ned( ) : vo id
Elev ator
- m oving : Bo olean = false
- sum moned : Boo lea n = false
- c urrentFlo or : Loc ation
- d estina tionFloor : Loc a tion
- tra velTim e : Intege r = 5
+ ride( ) : v oid
+ req uestEleva to r( ) : void
+ enterElev ator( ) : v oid
+ exitElev ator( ) : v oid
+ dep artEle vator( ) : void
+ getButton( ) : Button
+ getDoo r( ) : Door
 2002 Prentice Hall. All rights reserved.
+ ringBell( ) : v oid
Butto n
- pre ssed : Boolean = fa lse
+ re setButton( ) : v oid
+ p ressButton( ) : v oid
Do or
- ope n : Boolean = false
+ op enDoor( ) : v oid
+ c loseDo or( ) : vo id
9.23 Thinking About Objects (cont.)
• Continue implementation
– Transform design (i.e., class diagram) to code
– Generate “skeleton code” with our design
• Use class Elevator as example
• Two steps (incorporating inheritance)
 2002 Prentice Hall. All rights reserved.
9.23 Thinking About Objects (cont.)
Step 1
public class Elevator extends Location {
// class constructor
public Elevator() {}
}
 2002 Prentice Hall. 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
29
29
30
31
32
33
34
35
36
// Elevator.java
// Generated using class diagrams 9.38 and 9.39
public class Elevator extends Location {
// class 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;
Outline
Step 2
Implement abstract
classes
// class constructor
public Elevator() {}
// class methods
public void ride() {}
public void requestElevator() {}
public void enterElevator() {}
public void exitElevator() {}
public void departElevator() {}
Implement abstract classes
// method overriding getButton
public Button getButton()
{
return elevatorButton;
}
// method overriding getDoor
public Door getDoor()
{
return elevatorDoor;
}
}
 2002 Prentice Hall.
All rights reserved.
9.24 (Optional) Discovering Design
Patterns: Introducing Creational, Structural
and Behavioral Design Patterns
• Design-patterns discussion
– Discuss each type
• Creational
• Structural
• Behavioral
– Discuss importance
– Discuss how we can use each pattern in Java
 2002 Prentice Hall. All rights reserved.
9.24 Discovering Design Patterns (cont.)
• We also introduce
– Concurrent design patterns
• Used in multithreaded systems
• Chapter 15
– Architectural patterns
• Specify how subsystems interact with each other
• Chapter 17
 2002 Prentice Hall. All rights reserved.
Se c tio n
Cre a tiona l d e sig n p a tte rns
Struc tura l d e sig n p a tte rns
Be ha vio ra l d e sig n p a tte rns
9.24
Singleton
Proxy
Memento
State
13.18
Factory Method
Adapter
Bridge
Composite
Chain-of-Responsibility
Command
Observer
Strategy
Template Method
17.11
Abstract Factory
Decorator
Facade
21.12
Prototype
Fig. 9.40 The 18 Ga ng -of-four d esig n p a tterns d isc ussed
 2002 Prentice Hall. All rights reserved.
Iterator
in
Ja va Ho w to Pro g ra m 4/ e .
Sec tion
Conc urrent d esig n p a tterns
15.13
Single-Threaded Execution
Guarded Suspension
Balking
Read/Write Lock
Two-Phase Termination
17.11
Arc hitec tura l p a tterns
Model-View-Controller
Layers
Fig. 9.41 Conc urrent d esig n p a tterns a nd a rc hitec tura l p a tterns d isc ussed in Ja va Ho w to
Pro g ra m , 4/ e .
 2002 Prentice Hall. All rights reserved.
9.24 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
 2002 Prentice Hall. All rights reserved.
9.24 Discovering Design Patterns (cont.)
• 5 creational design patterns
–
–
–
–
–
Abstract Factory
Builder
Factory Method
Prototype
Singleton
 2002 Prentice Hall. All rights reserved.
(Chapter 17)
(not discussed)
(Chapter 13)
(Chapter 21)
(Chapter 9)
9.24 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
 2002 Prentice Hall. 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
Outline
// Singleton.java
// Demonstrates Singleton design pattern
package com.deitel.jhtp4.designpatterns;
Singleton.java
public final class Singleton {
// Singleton object returned by method getSingletonInstance
private static Singleton singleton;
private constructor
Line 11
ensures
private constructor
only objects
class Singleton can
// constructor prevents instantiation from other
ensures only class
private Singleton()
instantiate Singleton object
Singleton can
{
instantiate
System.err.println( "Singleton object created." );
Singleton object
}
// create Singleton and ensure only one Singleton instance
public static Singleton getSingletonInstance()
{
// instantiate Singleton if null
if ( singleton == null )
singleton = new Singleton();
Lines 20-23
Instantiate
Singleton object
only once, but return
same reference
return singleton;
}
}
Instantiate Singleton object only
once, but return same reference
 2002 Prentice Hall.
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
Outline
// SingletonExample.java
// Attempt to create two Singleton objects
package com.deitel.jhtp4.designpatterns;
SingletonExample
.java
public class SingletonExample {
// run SingletonExample
public static void main( String args[] )
{
Singleton firstSingleton;
Singleton secondSingleton;
Line 14
Create Singleton instance
Create Singleton
instance
// create Singleton objects
firstSingleton = Singleton.getSingletonInstance();
secondSingleton = Singleton.getSingletonInstance();
// the "two" Singletons should refer to same Singleton
if ( firstSingleton == secondSingleton )
System.out.println( "firstSingleton and " +
"secondSingleton refer to the same Singleton " +
"object" );
Line 15
Get same Singleton
instance
}
}
Get same Singleton instance
 2002 Prentice Hall.
All rights reserved.
9.24 Discovering Design Patterns (cont.)
• Structural design patterns
– Describe common ways to organize classes and objects
–
–
–
–
–
–
–
Adapter
Bridge
Composite
Decorator
Facade
Flyweight
Proxy
 2002 Prentice Hall. All rights reserved.
(Chapter 13)
(Chapter 13)
(Chapter 13)
(Chapter 17)
(Chapter 17)
(not discussed)
(Chapter 9)
9.24 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
 2002 Prentice Hall. All rights reserved.
9.24 Discovering Design Patterns (cont.)
• Behavioral design patterns
– Model how objects collaborate with one another
– Assign responsibilities to algorithms
 2002 Prentice Hall. All rights reserved.
9.24 Discovering Design Patterns (cont.)
• Behavioral design patterns
–
–
–
–
–
–
–
–
–
–
–
Chain-of-Responsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer
State
Strategy
Template Method
Visitor
 2002 Prentice Hall. All rights reserved.
(Chapter 13)
(Chapter 13)
(not discussed)
(Chapter 21)
(not discussed)
(Chapter 9)
(Chapter 13)
(Chapter 9)
(Chapter 13)
(Chapter 13)
(not discussed)
9.24 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
 2002 Prentice Hall. All rights reserved.
9.24 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?
 2002 Prentice Hall. All rights reserved.
9.24 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
 2002 Prentice Hall. All rights reserved.