Escolar Documentos
Profissional Documentos
Cultura Documentos
Outline
9.1 Introduction
9.2 Superclasses and Subclasses
9.3 protected Members
9.4 Relationship between Superclass Objects and Subclass
Objects
9.5 Constructors and Finalizers in Subclasses
9.6 Implicit Subclass-Object-to-Superclass-Object Conversion
9.7 Software Engineering with Inheritance
9.8 Composition vs. Inheritance
9.9 Case Study: Point, Circle, Cylinder
9.10 Introduction to Polymorphism
9.11 Type Fields and switch Statements
9.12 Dynamic Method Binding
9.13 final Methods and Classes
• 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
• 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
• “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
CommunityMember is a direct
superclass of Employee
Co mmuni t y Membe r
CommunityMember
is an indirect superclass
of Faculty Empl o y e e St udent Al umni
Fac ul t y St a f f
Admi ni s t r at o r Te ac he r
Sha pe
Page 11
34 // get y coordinate Outline
35 public int getY()
36 { Point.java
37 return y;
38 }
39
40 // convert into a String representation
41 public String toString()
42 {
43 return "[" + x + ", " + y + "]";
44 }
45
46 } // end class Point
Page 12
1 // Fig. 9.5: Circle.java Outline
2 // Definition of class Circle Circle is a Point subclass
3 Circle.java
4 public class Circle extends Point { // inherits from Point
5 protected double radius;
6 Circle inherits Point’s Line 4
7 // no-argument constructor Circle is a Point
8 public Circle() protected variables and public
9 { methods (except for constuctor) subclass
10 // implicit call to superclass constructor occurs here
11 setRadius( 0 );
12 }
Line 4
13 Circle inherits
Implicit call to Point constructor
14 // constructor Point’s protected
15 public Circle( double circleRadius, int xCoordinate,
variables and public
16 int yCoordinate )
17 { methods (except for
18 // call superclass constructor to set coordinates constuctor)
19 super( xCoordinate, yCoordinate );
20
21 // set radius Line 10
22 setRadius( circleRadius ); Explicit call to Point Implicit call to Point
23 }
24
constructor using super constructor
25 // set radius of Circle
26 public void setRadius( double circleRadius ) Line 19
27 {
28 radius = ( circleRadius >= 0.0 ? circleRadius : 0.0 );
Explicit call to Point
29 } constructor using
30 super
Page 13
31 // get radius of Circle Outline
32 public double getRadius()
33 { Circle.java
34 return radius;
35 }
36 Lines 44-48
37 // calculate area of Circle
38 public double area()
Override method
39 { toString of class
40 return Math.PI * radius * radius; Point by using same
41 }
42
signature
Override method toString of class
43 // convert the Circle to a String Point by using same signature
44 public String toString()
45 {
46 return "Center = " + "[" + x + ", " + y + "]" +
47 "; Radius = " + radius;
48 }
49
50 } // end class Circle
Page 14
1 // Fig. 9.6: InheritanceTest.java Outline
2 // Demonstrating the "is a" relationship
3 InheritanceTest.ja
4 // Java core packages va
5 import java.text.DecimalFormat;
6
7 // Java extension packages Lines 18-19
8 import javax.swing.JOptionPane; Instantiate objects
9
10 public class InheritanceTest { Line 22
11 Instantiate Point and Circle objects
Circle invokes method
12 // test classes Point and Circle
13 public static void main( String args[] )
toString
14 {
15 Point point1, point2; Line 26
16 Circle circle1, circle2; Superclass object
17 Circle invokes its overridden
references subclass
18 point1 = new Point( 30, 50 ); toString method
19 circle1 = new Circle( 2.7, 120, 89 );
20 Line 29
21 String output = "Point point1: " + point1.toString() + Point invokes Circle’s
22 "\nCircle circle1: " + circle1.toString(); toString method
23 Superclass object can
(polymorphism and
24 // use "is a" relationship to refer to a Circlereference subclass object
dynamic binding)
25 // with a Point reference
26 point2 = circle1; // assigns Circle to a Point reference
Line 33
27 Point still invokes Circle’s
Downcast Point to
28 output += "\n\nCircle circle1 (via point2 reference): " +
29 point2.toString();
overridden toStringCircle
method
30
31 // use downcasting (casting a superclass reference to a
32 // subclass data type) to assign point2 to circle2
33 circle2 = ( Circle ) point2; Downcast Point to Circle
34
Page 15
35 output += "\n\nCircle circle1 (viaCircle invokes
circle2): " + its overridden Outline
36 circle2.toString(); toString method
37 InheritanceTest.
38 DecimalFormat precision2 = new DecimalFormat( "0.00" );
39 output += "\nArea of c (via circle2): " + java
40 precision2.format( circle2.area() ); Circle invokes method area
41
42 // attempt to refer to Point object with Circle reference
Line 36
43 if ( point1 instanceof Circle ) { Circle invokes its
44 circle2 = ( Circle ) point1; overridden toString
Use instanceof to determine
45 output += "\n\ncast successful"; if Point refers to Circle
46 }
method
47 else
48 output += "\n\npoint1 does not refer to a Circle"; Line 40
49
Circle
If Point refers to invokes
Circle,
50 JOptionPane.showMessageDialog( null, output,
51 "Demonstrating the \"is a\" relationship", cast Point as method
Circlearea
52 JOptionPane.INFORMATION_MESSAGE );
53
54 System.exit( 0 );
Line 43
55 } Use instanceof to
56 determine if Point
57 } // end class InheritanceTest
refers to Circle
Line 44
If Point refers to
Circle, cast Point
as Circle
Page 16
Fig. 9.6 Assigning subclass references to superclass references
• finalize method
– Garbage collection
– Subclass finalize method
• should invoke superclass finalize method
Page 20
32 // convert the Circle to a String Outline
33 public String toString()
34 { Circle.java
35 return "Center = " + super.toString() +
36 "; Radius = " + radius;
37 }
38
39 } // end class Circle
Page 21
1 // Fig. 9.9: Test.java Outline
2 // Demonstrate when superclass and subclass
3 // constructors and finalizers are called. Test.java
4 public class Test { Instantiate Circle objects
5
6 // test when constructors and finalizers are called Lines 10-11
7 public static void main( String args[] ) Instantiate Circle
8 {
9 Circle circle1, circle2; objects
10
11 circle1 = new Circle( 4.5, 72, 29 );
12 circle2 = new Circle( 10, 5, 5 );
Line 17
13 Invoke Circle’s
14 circle1 = null; // mark for garbage collection method finalize by
15 circle2 = null; // mark for garbage collection
calling System.gc
16
17 System.gc(); // call the garbage collector
18 }
19 Invoke Circle’s method
20 } // end class Test
finalize by calling System.gc
• Inheritance
– Create class (subclass) from existing one (superclass)
• Subclass creation does not affect superclass
– New class inherits attributes and behaviors
– Software reuse
• Inheritance
– “Is a” relationship
– Teacher is an Employee
• Composition
– “Has a” relationship
– Employee has a TelephoneNumber
Page 28
1 // Fig. 9.11: Test.java Outline
2 // Applet to test class Point
3 Test.java
4 // Java extension packages
5 import javax.swing.JOptionPane;
6 Line 15
7 // Deitel packages Instantiate Point
8 import com.deitel.jhtp4.ch09.Point;
9 object
10 public class Test {
11 Instantiate Point object
12 // test class Point
Lines 18-19
13 public static void main( String args[] ) Methods getX and
14 { getY read Point’s
15 Point point = new Point( 72, 115 );
protected variables
16
17 // get coordinates
18 String output = "X coordinate is " + point.getX() +
19 "\nY coordinate is " + point.getY();
20
21 // set coordinates
22 point.setPoint( 10, 10 ); Methods getX and getY read
23 Point’s protected variables
24 // use implicit call to point.toString()
25 output += "\n\nThe new location of point is " + point;
26
27 JOptionPane.showMessageDialog( null, output,
28 "Demonstrating Class Point",
29 JOptionPane.INFORMATION_MESSAGE );
30
31 System.exit( 0 );
32 }
33
34 } // end class Test
Page 29
Fig. 9.11 Testing class Point
Page 31
32 // get radius of Circle Outline
33 public double getRadius()
34 { Circle.java
35 return radius;
36 }
37
38 // calculate area of Circle
39 public double area()
40 {
41 return Math.PI * radius * radius;
42 }
43
44 // convert the Circle to a String
45 public String toString()
46 {
47 return "Center = " + "[" + x + ", " + y + "]" +
48 "; Radius = " + radius;
49 }
50
51 } // end class Circle
Page 32
1 // Fig. 9.13: Test.java Outline
2 // Applet to test class Circle
3 Test.java
4 // Java core packages
5 import java.text.DecimalFormat;
6 Line 19
7 // Java extension packages Instantiate Circle
8 import javax.swing.JOptionPane;
9 object
10 // Deitel packages
11 import com.deitel.jhtp4.ch09.Circle;
12
Lines 25 and 28
13 public class Test { Calls to methods
14 Instantiate Circle object getRadius and
15 // test class Circle
setRadius read and
16 public static void main( String args[] )
17 { manipulate Circle’s
18 // create a Circle Calls to methods protectedand
getRadius variables
19 Circle circle = new Circle( 2.5, 37, 43 ); setRadius read and manipulate
20 DecimalFormat precision2 = new DecimalFormat( "0.00" );
Circle’s protected variables
21 Lines 23-24 and 29
22 // get coordinates and radius Calls to methods getX,
23 String output = "X coordinate is " + circle.getX() +
24 "\nY coordinate is " + circle.getY() +
getY and setPoint
25 "\nRadius is " + circle.getRadius(); read and manipulate
26 Circle’s inherited
27 // set coordinates and radius Calls to methods getX, getY and
protected variables
28 circle.setRadius( 4.25 ); setPoint read and manipulate Circle’s
29 circle.setPoint( 2, 2 );
30
inherited protected variables
31 // get String representation of Circle and calculate area
32 output +=
33 "\n\nThe new location and radius of c are\n" + circle +
34 "\nArea is " + precision2.format( circle.area() );
35 Page 33
36 JOptionPane.showMessageDialog( null, output, Outline
37 "Demonstrating Class Circle",
38 JOptionPane.INFORMATION_MESSAGE ); Test.java
39
40 System.exit( 0 );
41 }
42
43 } // end class Test
Page 34
Fig. 9.13 Testing class Circle
Page 36
32 // get height of Cylinder Outline
33 public double getHeight()
34 { Cylinder.java
35 return height;
Override method area
36 } of class Circle
37 Lines 39-43
38 // calculate area of Cylinder (i.e., surface area)
39 public double area()
Override method area
40 { of class Circle
41 return 2 * super.area() +
42 2 * Math.PI * radius * height;
43 }
44
45 // calculate volume of Cylinder
46 public double volume()
47 {
48 return super.area() * height;
49 }
50
51 // convert the Cylinder to a String
52 public String toString()
53 {
54 return super.toString() + "; Height = " + height;
55 }
56
57 } // end class Cylinder
Page 37
1 // Fig. 9.15: Test.java Outline
2 // Application to test class Cylinder
3 Test.java
4 // Java core packages
5 import java.text.DecimalFormat;
6 Line 19
7 // Java extension packages Instantiate Cylinder
8 import javax.swing.JOptionPane;
9 object
10 // Deitel packages
11 import com.deitel.jhtp4.ch09.Cylinder;
12
Lines 23-31
13 public class Test { Method calls read and
14 Instantiate Cylinder object manipulate
15 // test class Cylinder
Cylinder’s
16 public static void main( String args[] )
17 { protected variables
18 // create Cylinder and inherited
19 Cylinder cylinder = new Cylinder( 5.7, 2.5, 12, 23 );
protected variables
20 DecimalFormat precision2 = new DecimalFormat( "0.00" );
21
22 // get coordinates, radius and height
23 String output = "X coordinate is " + cylinder.getX() +
24 "\nY coordinate is " + cylinder.getY() +
25 "\nRadius is " + cylinder.getRadius() +
26 "\nHeight is " + cylinder.getHeight();
27
28 // set coordinates, radius and height
29 cylinder.setHeight( 10 );
30 cylinder.setRadius( 4.25 ); Method calls read and manipulate
31 cylinder.setPoint( 2, 2 ); Cylinder’s protected variables
32 and inherited protected variables
Page 38
33 // get String representation of Cylinder and calculate Outline
34 // area and volume
35 output += "\n\nThe new location, radius " + Test.java
36 "and height of cylinder are\n" + cylinder +
37 "\nArea is " + precision2.format( cylinder.area() ) +
38 "\nVolume is " + precision2.format( cylinder.volume() );
39
40 JOptionPane.showMessageDialog( null, output,
41 "Demonstrating Class Cylinder",
42 JOptionPane.INFORMATION_MESSAGE );
43
44 System.exit( 0 );
45 }
46
47 } // end class Test
Page 39
Fig. 9.15 Testing class Test
• 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
• 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
• final method
– Cannot be overridden in subclass
– Compiler can optimize the program by removing calls to
final methods and replacing them with the expanded code
at each method call location – inlining the code
• final class
– Cannot be superclass (cannot be extended)
• A class cannot inherit from a final classes
• Every method is implicitly final
• 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
Page 49
32 // Abstract method that must be implemented for each Outline
33 // derived class of Employee from which objects
34 // are instantiated. Employee.java
35 public abstract double earnings();
36
37 } // end class Employee Line 35
Subclasses must implement Subclasses must
abstract method implement abstract
method
Page 50
1 // Fig. 9.17: Boss.java Boss is an Employee subclass Outline
2 // Boss class derived from Employee.
3 Boss.java
4 public final class Boss extends Employee {
5 private double weeklySalary; Boss inherits Employee’s public
6 Line 4
methods (except for constuctor)
7 // constructor for class Boss Boss is an Employee
8 public Boss( String first, String last, double salary )
9 { subclass
10 super( first, last ); // call superclass constructor
11 setWeeklySalary( salary );
12 } Explicit call to Employee Line 4
13 constructor using super Boss inherits
14 // set Boss's salary Employee’s public
15 public void setWeeklySalary( double salary )
16 {
methods (except for
17 weeklySalary = ( salary > 0 ? salary : 0 ); constuctor)
18 }
19 Required to implement Employee’s
Line 10
20 // get Boss's pay
21 public double earnings() method earnings (polymorphism)
Explicit call to
22 { Employee constructor
23 return weeklySalary;
24 }
using super
25
26 // get String representation of Boss's name Lines 21-24
27 public String toString()
28 {
Required to implement
29 return "Boss: " + super.toString(); Employee’s method
30 } earnings
31
32 } // end class Boss
(polymorphism)
Page 51
1 // Fig. 9.18: CommissionWorker.java CommissionWorker is an Outline
2 Employee subclass
// CommissionWorker class derived from Employee
3 CommissionWorker
4 public final class CommissionWorker extends Employee {
5 private double salary; // base salary per week .java
6 private double commission; // amount per item sold
7 private int quantity; // total items sold for week
8
Line 4
9 // constructor for class CommissionWorker CommissionWorker
10 public CommissionWorker( String first, String last, is an Employee
11 double salary, double commission, int quantity )
12 {
subclass
13 super( first, last ); // call superclass constructor
14 setSalary( salary );
Explicit call to Employee Line 13
15 setCommission( commission );
16 setQuantity( quantity ); constructor using super Explicit call to
17 } Employee constructor
18 using super
19 // set CommissionWorker's weekly base salary
20 public void setSalary( double weeklySalary )
21 {
22 salary = ( weeklySalary > 0 ? weeklySalary : 0 );
23 }
24
25 // set CommissionWorker's commission
26 public void setCommission( double itemCommission )
27 {
28 commission = ( itemCommission > 0 ? itemCommission : 0 );
29 }
30
Page 52
31 // set CommissionWorker's quantity sold Outline
32 Required to) implement Employee’s
public void setQuantity( int totalSold
33 { CommissionWorker
34
method earnings; this implementation
quantity = ( totalSold > 0 ? totalSold : 0 );
35 } differs from that in Boss .java
36
37 // determine CommissionWorker's earnings
38 public double earnings()
Lines 38-41
39 { Required to implement
40 return salary + commission * quantity; Employee’s method
41 } earnings; this
42
43 // get String representation of CommissionWorker's name implementation differs
44 public String toString() from that in Boss
45 {
46 return "Commission worker: " + super.toString();
47 }
48
49 } // end class CommissionWorker
Page 53
1 // Fig. 9.19: PieceWorker.java PieceWorker is an Outline
2 Employee subclass
// PieceWorker class derived from Employee
3 PieceWorker.java
4 public final class PieceWorker extends Employee {
5 private double wagePerPiece; // wage per piece output
6 private int quantity; // output for week Line 4
7 PieceWorker is an
8 // constructor for class PieceWorker
9 public PieceWorker( String first, String last, Employee subclass
10 double wage, int numberOfItems )
11 {
12 super( first, last ); // call superclass constructor
Line 12
13 setWage( wage ); Explicit call to
14 setQuantity( numberOfItems); Explicit call to Employee Employee constructor
15 } constructor using super using super
16
17 // set PieceWorker's wage
18 public void setWage( double wage ) Lines 30-33
19 {
20 wagePerPiece = ( wage > 0 ? wage : 0 );
Implementation of
21 } Employee’s method
22 earnings; differs
23 // set number of items output
24 public void setQuantity( int numberOfItems )
from that of Boss and
25 { CommissionWorker
26 quantity = ( numberOfItems > 0 ? numberOfItems : 0 );
27 }
28 Implementation of Employee’s method
29 // determine PieceWorker's earnings earnings; differs from that of Boss
30 public double earnings()
31 { and CommissionWorker
32 return quantity * wagePerPiece;
33 }
34
Page 54
35 public String toString() Outline
36 {
37 return "Piece worker: " + super.toString(); PieceWorker.java
38 }
39
40 } // end class PieceWorker
Page 55
1 // Fig. 9.20: HourlyWorker.java HourlyWorker is an Outline
2 // Definition of class HourlyWorker Employee subclass
3 HourlyWorker.java
4 public final class HourlyWorker extends Employee {
5 private double wage; // wage per hour
6 private double hours; // hours worked for week Line 4
7 PieceWorker is an
8 // constructor for class HourlyWorker
9 public HourlyWorker( String first, String last, Employee subclass
10 double wagePerHour, double hoursWorked )
11 {
12 super( first, last ); // call superclass constructor
Line 12
13 setWage( wagePerHour ); Explicit call to
14 setHours( hoursWorked ); Explicit call to Employee Employee constructor
15 } constructor using super using super
16
17 // Set the wage
18 public void setWage( double wagePerHour ) Line 31
19 {
20 wage = ( wagePerHour > 0 ? wagePerHour : 0 );
Implementation of
21 } Employee’s method
22 Implementation of Employee’s
earnings; method
differs from
23 // Set the hours worked earnings; differs from
thatthat of other
of other Employee
24 public void setHours( double hoursWorked )
Employee subclasses
subclasses
25 {
26 hours = ( hoursWorked >= 0 && hoursWorked < 168 ?
27 hoursWorked : 0 );
28 }
29
30 // Get the HourlyWorker's pay
31 public double earnings() { return wage * hours; }
32
Page 56
33 public String toString() Outline
34 {
35 return "Hourly worker: " + super.toString(); HourlyWorker.java
36 }
37
38 } // end class HourlyWorker
Page 57
1 // Fig. 9.21: Test.java Outline
2 // Driver for Employee hierarchy
3 Test.java
4 // Java core packages
5 import java.text.DecimalFormat;
6 Line 15
7 // Java extension packages Test cannot
8 import javax.swing.JOptionPane; Test cannot instantiate Employee instantiate Employee
9
10 public class Test { but can reference one but can reference one
11
12 // test Employee hierarchy
13 public static void main( String args[] ) Lines 18-28
14 { Instantiate one instance each
Instantiate oneofinstance
15 Employee employee; // superclass reference Employeeeach subclasses
of Employee
16 String output = "";
17 subclasses
18 Boss boss = new Boss( "John", "Smith", 800.0 );
19
20 CommissionWorker commisionWorker =
21 new CommissionWorker(
22 "Sue", "Jones", 400.0, 3.0, 150 );
23
24 PieceWorker pieceWorker =
25 new PieceWorker( "Bob", "Lewis", 2.5, 200 );
26
27 HourlyWorker hourlyWorker =
28 new HourlyWorker( "Karen", "Price", 13.75, 40 );
29
30 DecimalFormat precision2 = new DecimalFormat( "0.00" );
31
Page 58
32 // Employee reference to a Boss Use Employee to reference Boss Outline
33 employee = boss;
34 Test.java
35 output += employee.toString() + " earned $" +
36 precision2.format( employee.earnings() ) + "\n" +
37 boss.toString() + " earned $" + Line 33
38 precision2.format( boss.earnings() ) + "\n"; Method employee.earnings
Use Employee to
39
40 // Employee reference to a CommissionWorker
dynamically binds to method
reference Boss
41 employee = commissionWorker; boss.earnings
42
43 output += employee.toString() + " earned $" +
Line 36
44 precision2.format( employee.earnings() ) + "\n" + Method
45 commissionWorker.toString() + " earned $" + employee.earning
46 precision2.format(
s dynamically binds to
47 commissionWorker.earnings() ) + "\n";
48 Do same for CommissionWorker
method
49 // Employee reference to a PieceWorker and PieceWorker
boss.earnings
50 employee = pieceWorker;
51
52 output += employee.toString() + " earned $" + Lines 41-55
53 precision2.format( employee.earnings() ) + "\n" + Do same for
54 pieceWorker.toString() + " earned $" +
55 precision2.format( pieceWorker.earnings() ) + "\n";
CommissionWorker
56 and PieceWorker
Page 59
57 // Employee reference to an HourlyWorker Outline
58 employee = hourlyWorker;
59 Test.java
60 output += employee.toString() + " earned $" +
61 precision2.format( employee.earnings() ) + "\n" +
62 hourlyWorker.toString() + " earned $" + Lines 58-63
63 precision2.format( hourlyWorker.earnings() ) + "\n";
64
Repeat for
65 JOptionPane.showMessageDialog( null, output, HourlyWorker
66 "Demonstrating Polymorphism",
67 JOptionPane.INFORMATION_MESSAGE );
68 Repeat for HourlyWorker
69 System.exit( 0 );
70 }
71
72 } // end class Test
Page 60
9.17 New Classes and Dynamic Binding
Page 63
1 // Fig. 9.23: Point.java Point inherits Shape’s Outline
2 // Definition of class Point public methods
3 Point.java
4 public class Point extends Shape {
5 protected int x, y; // coordinates of the Point
6 Line 4
7 // no-argument constructor Point inherits
8 public Point() protected members prevent
9 { Shape’s public
clients from direct access (unless
10 setPoint( 0, 0 );
clients are Point subclasses or methods
11 }
12 are in same package)
13 // constructor Line 5
14 public Point( int xCoordinate, int yCoordinate ) protected members
15 {
16 setPoint( xCoordinate, yCoordinate );
prevent clients from
17 } direct access (unless
18 clients are Point
19 // set x and y coordinates of Point
20 public void setPoint( int xCoordinate, int yCoordinate )
subclasses or are in
21 { same package)
22 x = xCoordinate;
23 y = yCoordinate;
24 }
25
26 // get x coordinate
27 public int getX()
28 {
29 return x;
30 }
31
Page 64
32 // get y coordinate Outline
33 public int getY()
34 { Point.java
35 return y;
36 }
37 Lines 45-48
38 // convert point into String representation
39 public String toString()
Implementation of
40 { Shape’s method
41 return "[" + x + ", " + y + "]"; getName
42 } Implementation
of Shape’s
43
44 // return shape name method getName *** Note ***
45 public String getName()
46 {
47 return "Point";
48 }
49
50 } // end class Point
Point does not override methods
area and volume, because points
have neither area nor volume
Page 65
1 // Fig. 9.24: Circle.java Circle inherits variables/methods Outline
2 // Definition of class Circle from Point and Shape
3 Circle.java
4 public class Circle extends Point { // inherits from Point
5 protected double radius;
6 Line 4
7 // no-argument constructor Circle inherits
8 public Circle()
9 { variables/methods from
10 // implicit call to superclass constructor here Point and Shape
11 setRadius( 0 );
12 }
13 Lines 5 and 24-34
14 // constructor Methods for
15 public Circle( double circleRadius, int xCoordinate,
16 int yCoordinate )
reading/setting
17 { protected value
18 // call superclass constructor
19 super( xCoordinate, yCoordinate ); Methods for reading/setting
20 protected value
21 setRadius( circleRadius );
22 }
23
24 // set radius of Circle
25 public void setRadius( double circleRadius )
26 {
27 radius = ( circleRadius >= 0 ? circleRadius : 0 );
28 }
29
30 // get radius of Circle
31 public double getRadius()
32 {
33 return radius;
34 }
35 Page 66
36 // calculate area of Circle Outline
37 public double area()
38 { Circle.java
39 return Math.PI * radius * radius;
40 }
41 Override method area but not method volume
Lines 37-40
42 (circles do not have volume)
// convert Circle to a String represention Override method area
43 public String toString()
44 { but not method
45 return "Center = " + super.toString() + volume (circles do not
46 "; Radius = " + radius; have volume)
47 } Implementation of Shape’s
48
method getName
49 // return shape name Lines 50-53
50 public String getName()
51 {
Implementation of
52 return "Circle"; Shape’s method
53 } getName
54
55 } // end class Circle
Page 67
1 // Fig. 9.25: Cylinder.java Cylinder inherits variables Outline
2 // Definition of class Cylinder. and methods from Point,
3 Cylinder.java
4 public class Cylinder extends Circle {
Circle and Shape
5 protected double height; // height of Cylinder
6 Line 4
7 // no-argument constructor Cylinder inherits
8 public Cylinder()
9 { variables and methods
10 // implicit call to superclass constructor here from Point, Circle
11 setHeight( 0 ); and Shape
12 }
13
14 // constructor
15 public Cylinder( double cylinderHeight,
16 double cylinderRadius, int xCoordinate,
17 int yCoordinate )
18 {
19 // call superclass constructor
20 super( cylinderRadius, xCoordinate, yCoordinate );
21
22 setHeight( cylinderHeight );
23 }
24
25 // set height of Cylinder
26 public void setHeight( double cylinderHeight )
27 {
28 height = ( cylinderHeight >= 0 ? cylinderHeight : 0 );
29 }
30
Page 68
31 // get height of Cylinder Outline
32 public double getHeight()
33 { Cylinder.java
34 return height;
35 }
36 Lines 38-47
37 // calculate area of Cylinder (i.e., surface area)
38 public double area()
Override methods
39 { area and volume
40 return 2 * super.area() + 2 * Math.PI * radius * height;
41 }
Lines 56-59
42 Override methods area
43 // calculate volume of Cylinder Implementation of
and volume
44 public double volume() Shape’s method
45 { getName
46 return super.area() * height;
47 }
48
49 // convert Cylinder to a String representation
50 public String toString()
51 {
52 return super.toString() + "; Height = " + height;
53 }
54
55 // return shape name
56 public String getName()
Implementation of Shape’s
57 { method getName
58 return "Cylinder";
59 }
60
61 } // end class Cylinder
Page 69
1 // Fig. 9.26: Test.java Outline
2 // Class to test Shape, Point, Circle, Cylinder hierarchy
3 Test.java
4 // Java core packages
5 import java.text.DecimalFormat;
6 Lines 16-18
7 // Java extension packages
Instantiate one instance
8 import javax.swing.JOptionPane; Instantiate one instance
9 each of Shape
each of Shape subclasses
10 public class Test { subclasses
11
12 // test Shape hierarchy
13 public static void main( String args[] ) Lines 21-30
14 { Create three Shapes to
15 // create shapes
16 Point point = new Point( 7, 11 );
reference each subclass
17 Circle circle = new Circle( 3.5, 22, 8 ); object
18 Cylinder cylinder = new Cylinder( 10, 3.3, 10, 10 );
19
20 // create Shape array
21 Shape arrayOfShapes[] = new Shape[ 3 ];
Create three Shapes to
22 reference each subclass object
23 // aim arrayOfShapes[ 0 ] at subclass Point object
24 arrayOfShapes[ 0 ] = point;
25
26 // aim arrayOfShapes[ 1 ] at subclass Circle object
27 arrayOfShapes[ 1 ] = circle;
28
29 // aim arrayOfShapes[ 2 ] at subclass Cylinder object
30 arrayOfShapes[ 2 ] = cylinder;
31
Page 70
32 // get name and String representation of each shape Outline
33 String output =
34 point.getName() + ": " + point.toString() + "\n" + Test.java
35 circle.getName() + ": " + circle.toString() + "\n" +
36 cylinder.getName() + ": " + cylinder.toString();
37 Line 43
38 DecimalFormat precision2 = new DecimalFormat( "0.00" ); Dynamically bind bind
Dynamically
39
40 // loop through arrayOfShapes and get name,
method method
getName getName
41 // area and volume of each shape in arrayOfShapes
42 for ( int i = 0; i < arrayOfShapes.length; i++ ) {
43 output += "\n\n" + arrayOfShapes[ i ].getName() +
Line 46bind method
Dynamically
44 ": " + arrayOfShapes[ i ].toString() + Dynamically
area for Circlebind
and
45 "\nArea = " + method area
Cylinder for
objects
46 precision2.format( arrayOfShapes[ i ].area() ) +
Circle and
47 "\nVolume = " +
48 precision2.format( arrayOfShapes[ i ].volume() ); Cylinder objects
49 }
50
51 JOptionPane.showMessageDialog( null, output,
Line 48
52 "Demonstrating Polymorphism",
Dynamically Dynamically
bind method bind
53 JOptionPane.INFORMATION_MESSAGE ); volume for Cylinder object for
method volume
54
55 System.exit( 0 );
Cylinder object
56 }
57
58 } // end class Test
Page 71
Outline
Test.java
Page 72
9.19 Case Study: Creating and Using Interfaces
• Use interface Shape
– interface Used instead of an abstract class when there
are no instance variables or default method implementations to
inherit
• Interface
– Definition begins with interface keyword
– Classes implement an interface
– Class must define every method in the interface with the number
of arguments and return type specified in the interface
• If any methods are undefined, the class is abstract and ust be
declared so
– Contains public abstract methods
• Classes (that implement the interface) must implement these
methods
– A class can implement more than one interface
Page 74
1 // Fig. 9.28: Point.java Outline
2 // Definition of class Point
3 Point.java
4 public class Point extends Object implements Shape {
5 protected int x, y; // coordinates of the Point
6 Line 4
7 // no-argument constructor Point implements
8 public Point()
9 { interface Shape
10 setPoint( 0, 0 ); Point implements interface Shape
11 }
12
13 // constructor
14 public Point( int xCoordinate, int yCoordinate )
15 {
16 setPoint( xCoordinate, yCoordinate );
17 }
18
19 // Set x and y coordinates of Point
20 public void setPoint( int xCoordinate, int yCoordinate )
21 {
22 x = xCoordinate;
23 y = yCoordinate;
24 }
25
26 // get x coordinate
27 public int getX()
28 {
29 return x;
30 }
31
Page 75
32 // get y coordinate Outline
33 public int getY()
34 { Point.java
35 return y;
36 }
37 Lines 45-60
38 // convert point into String representation
39 public String toString()
Implement methods
40 { specified by interface
41 return "[" + x + ", " + y + "]"; Shape
42 }
43
44 // calculate area
45 public double area()
46 {
47 return 0.0;
48 }
49
50 // calculate volume Implement methods specified
51 public double volume()
52 { by interface Shape
53 return 0.0;
54 }
55
56 // return shape name
57 public String getName()
58 {
59 return "Point";
60 }
61
62 } // end class Point
Page 76
1 // Fig. 9.29: Circle.java Outline
2 // Definition of class Circle
3 Circle.java
4 public class Circle extends Point { // inherits from Point
5 protected double radius;
6 Line 4
7 // no-argument constructor Circle inherits variables/methods
Circle inherits
8 public Circle() from Point, including method
9 { variables/methods from
implementations of Shape
10 // implicit call to superclass constructor here Point, including
11 setRadius( 0 );
12 }
method implemen-
13 tations of Shape
14 // constructor
15 public Circle( double circleRadius, int xCoordinate,
16 int yCoordinate )
17 {
18 // call superclass constructor
19 super( xCoordinate, yCoordinate );
20
21 setRadius( circleRadius );
22 }
23
24 // set radius of Circle
25 public void setRadius( double circleRadius )
26 {
27 radius = ( circleRadius >= 0 ? circleRadius : 0 );
28 }
29
30 // get radius of Circle
31 public double getRadius()
32 {
33 return radius;
34 }
35 Page 77
36 // calculate area of Circle Outline
37 public double area()
38 { Circle.java
39 return Math.PI * radius * radius;
40 }
Override method toString
41 Lines 43-47
42 // convert Circle to a String represention
43 public String toString()
Override method
44 { toString
45 return "Center = " + super.toString() +
46 "; Radius = " + radius;
Lines 37-40 and 50-53
47 } Override methods area and
48 Override methods
getName but not method volume
49 // return shape name area and getName
50 public String getName()
51 {
but not method
52 return "Circle"; volume
53 }
54
55 } // end class Circle
Page 78
1 // Fig. 9.30: Cylinder.java Outline
2 // Definition of class Cylinder.
3 Cylinder.java
4 public class Cylinder extends Circle {
5 protected double height; // height of Cylinder
6 Line 4
7 // no-argument constructor Circle inherits variables/methods
Circle inherits
8 public Cylinder() from Point and Circle and
9 { variables/methods from
method implementations of Shape
10 // implicit call to superclass constructor here Point and Circle
11 setHeight( 0 );
12 }
and method
13 implementations of
14 // constructor Shape
15 public Cylinder( double cylinderHeight,
16 double cylinderRadius, int xCoordinate,
17 int yCoordinate )
18 {
19 // call superclass constructor
20 super( cylinderRadius, xCoordinate, yCoordinate );
21
22 setHeight( cylinderHeight );
23 }
24
25 // set height of Cylinder
26 public void setHeight( double cylinderHeight )
27 {
28 height = ( cylinderHeight >= 0 ? cylinderHeight : 0 );
29 }
30
31 // get height of Cylinder
32 public double getHeight()
33 {
34 return height;
35 } Page 79
36 Outline
37 // calculate area of Cylinder (i.e., surface area)
38 public double area() Cylinder.java
39 {
40 return 2 * super.area() + 2 * Math.PI * radius * height;
41 } Lines 50-53
42
43 // calculate volume of Cylinder
Override method
44 public double volume() Override method toString toString
45 {
46 return super.area() * height;
Line 38-59
47 } Override methods area,
48 Override methods
volume and getName
49 // convert Cylinder to a String representation area, volume and
50 public String toString() getName
51 {
52 return super.toString() + "; Height = " + height;
53 }
54
55 // return shape name
56 public String getName()
57 {
58 return "Cylinder";
59 }
60
61 } // end class Cylinder
Page 80
1 // Fig. 9.31: Test.java Outline
2 // Test Point, Circle, Cylinder hierarchy with interface Shape.
3 Test.java
4 // Java core packages
5 import java.text.DecimalFormat;
6 Fig. 9.31 is identical to
7 // Java extension packages Fig. 9.31 is identical
Fig. 9.26
8 import javax.swing.JOptionPane; to Fig. 9.26
9
10 public class Test {
11
12 // test Shape hierarchy
13 public static void main( String args[] )
14 {
15 // create shapes
16 Point point = new Point( 7, 11 );
17 Circle circle = new Circle( 3.5, 22, 8 );
18 Cylinder cylinder = new Cylinder( 10, 3.3, 10, 10 );
19
20 // create Shape array
21 Shape arrayOfShapes[] = new Shape[ 3 ];
22
23 // aim arrayOfShapes[ 0 ] at subclass Point object
24 arrayOfShapes[ 0 ] = point;
25
26 // aim arrayOfShapes[ 1 ] at subclass Circle object
27 arrayOfShapes[ 1 ] = circle;
28
29 // aim arrayOfShapes[ 2 ] at subclass Cylinder object
30 arrayOfShapes[ 2 ] = cylinder;
31
Page 81
32 // get name and String representation of each shape Outline
33 String output =
34 point.getName() + ": " + point.toString() + "\n" + Test.java
35 circle.getName() + ": " + circle.toString() + "\n" +
36 cylinder.getName() + ": " + cylinder.toString();
37
38 DecimalFormat precision2 = new DecimalFormat( "0.00" );
39
40 // loop through arrayOfShapes and get name,
41 // area and volume of each shape in arrayOfShapes
42 for ( int i = 0; i < arrayOfShapes.length; i++ ) {
43 output += "\n\n" + arrayOfShapes[ i ].getName() +
44 ": " + arrayOfShapes[ i ].toString() +
45 "\nArea = " +
46 precision2.format( arrayOfShapes[ i ].area() ) +
47 "\nVolume = " +
48 precision2.format( arrayOfShapes[ i ].volume() );
49 }
50
51 JOptionPane.showMessageDialog( null, output,
52 "Demonstrating Polymorphism",
53 JOptionPane.INFORMATION_MESSAGE );
54
55 System.exit( 0 );
56 }
57
58 } // end class Test
Page 82
Outline
Test.java
Output is identical to
that of Fig. 9.26
Output is identical
to that of Fig. 9.26
Page 83
9.19 Interfaces
• 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.
– An inner class is allowed to access directly all the instance
variables and methods of the outer class
– An inner class defined in a method is allowed access directly
to all the instance variables and methods of the outer class
object that defined it and any final local variables in the
method
Page 87
66 // convert to String in standard-time format Outline
67 public String toString()
68 { Time.java
69 DecimalFormat twoDigits = new DecimalFormat( "00" );
70
71 return ( ( getHour() == 12 || getHour() == 0 ) ? Lines 67-76
72 12 : getHour() % 12 ) + ":" +
73 twoDigits.format( getMinute() ) + ":" +
Override method
74 twoDigits.format( getSecond() ) + java.lang.Object
75 ( getHour() < 12 ? " AM" : " PM" ); .toString
76 }
77
78 } // end class Time
Override method
java.lang.Object.toString
Page 88
1 // Fig. 9.33: TimeTestWindow.java Outline
2 // Demonstrating the Time class set and get methods
3 TimeTestWindow.j
4 // Java core packages
5 import java.awt.*; JFrame provides basic window ava
6 import java.awt.event.*; attributes and behaviors
7
8 // Java extension packages
Line 11
9 import javax.swing.*; JFrame provides basic
10 window attributes and
11 public class TimeTestWindow extends JFrame {
12 private Time time;
behaviors
13 private JLabel hourLabel, minuteLabel, secondLabel;
14 private JTextField hourField, minuteField, Line 19
15 secondField, displayField; JFrame (unlike JApplet)
JFrame (unlike
16 private JButton exitButton;
17
has constructor JApplet) has
18 // set up GUI constructor
19 public TimeTestWindow() Instantiate Time object
20 {
21 super( "Inner Class Demonstration" ); Line 23
22 Instantiate Time object
23 time = new Time();
24
25 // create an instance of inner class ActionEventHandler Line 26
26 ActionEventHandler handler = new ActionEventHandler(); Instantiate object of
27
28 // set up GUI
inner-class that
29 Container container = getContentPane(); implements
30 container.setLayout( new FlowLayout() ); Instantiate object ofActionListener
inner-
31 class that implements
ActionListener
Page 89
32 hourLabel = new JLabel( "Set Hour" ); Outline
33 hourField = new JTextField( 10 );
34 hourField.addActionListener( handler ); TimeTestWindow.j
35 container.add( hourLabel );
36 container.add( hourField ); ava
37
38 minuteLabel = new JLabel( "Set minute" );
Line 34, 40, 46 and 55
39 minuteField = new JTextField( 10 );
40 minuteField.addActionListener( handler ); Register Action-
41 container.add( minuteLabel ); EventHandler with
42 container.add( minuteField );
GUI components
43
44 secondLabel = new JLabel( "Set Second" ); Register
45 secondField = new JTextField( 10 ); ActionEventHandler
46 secondField.addActionListener( handler );
47 container.add( secondLabel ); with GUI components
48 container.add( secondField );
49
50 displayField = new JTextField( 30 );
51 displayField.setEditable( false );
52 container.add( displayField );
53
54 exitButton = new JButton( "Exit" );
55 exitButton.addActionListener( handler );
56 container.add( exitButton );
57
58 } // end constructor
59
60 // display time in displayField
61 public void displayTime()
62 {
63 displayField.setText( "The time is: " + time );
64 }
65
Page 90
66 // create TimeTestWindow and display it Outline
67 public static void main( String args[] )
68 { TimeTestWindow.j
69 TimeTestWindow window = new TimeTestWindow();
70 ava
71 window.setSize( 400, 140 ); Define inner class that implements
72 window.setVisible( true );
73 } ActionListener interface Lines 77-78
74 Define inner class
75 // inner class definition for handling JTextField and
76 // JButton events
77 private class ActionEventHandler
Line 81
Must implement method actionPerformed
78 implements ActionListener { of ActionListener Must implement
79 method
80 // method to handle action events
actionPerformed
81 public void actionPerformed( ActionEvent event )
82 {
83 // user pressed exitButton Line 81
84 When user
if ( event.getSource() == exitButton ) presses JButton or Enter key,
When user presses
85 System.exit( 0 ); method
// terminate the actionPerformed
application is invoked
86 button or key, method
87 // user pressed Enter key in hourField actionPerformed
88 else if ( event.getSource() == hourField ) {
89 time.setHour(
is invoked
90 Integer.parseInt( event.getActionCommand() ) );
91 hourField.setText( "" ); Lines 84-99
92 } Determine actionDetermine
dependingaction
93
94 // user pressed Enter key in minuteField on where event depending
originated on where
95 else if ( event.getSource() == minuteField ) { event originated
96 time.setMinute(
97 Integer.parseInt( event.getActionCommand() ) );
98 minuteField.setText( "" );
99 }
Page 91
100 Outline
101 // user pressed Enter key in secondField
102 else if ( event.getSource() == secondField ) { TimeTestWindow.j
103 time.setSecond(
104 Integer.parseInt( event.getActionCommand() ) ); ava
105 secondField.setText( "" );
106 }
107
108 displayTime();
109 }
110
111 } // end inner class ActionEventHandler
112
113 } // end class TimeTestWindow
Page 92
Outline
TimeTestWindow.j
ava
Page 93
9.20 Inner Class Definitions (cont.)
Page 95
32 // register hourField event handler Outline
33 hourField.addActionListener(
34
35 // anonymous inner class
Define anonymous inner class that TimeTestWindow.j
36 new ActionListener() { implements ActionListener ava
37
38 public void actionPerformed( ActionEvent event )
39 {
Line 36
40 time.setHour( Define anonymous
41 Integer.parseInt( event.getActionCommand() ) ); inner class
42 hourField.setText( "" );
43 displayTime(); Inner class implements method
44 } actionPerformed Lines
of 38-44
45 ActionListener Inner class implements
46 } // end anonymous inner class
47
method
48 ); // end call to addActionListener Pass ActionListener as
actionPerformed
49 argument to GUI component’s
50 container.add( hourLabel );
method addActionListenerLine 33
51 container.add( hourField );
52 Pass Action-
53 minuteLabel = new JLabel( "Set minute" ); Listener to GUI
54 minuteField = new JTextField( 10 );
55
component’s method
56 // register minuteField event handler addAction-
57 minuteField.addActionListener( Listener
58
59 // anonymous inner class
60 new ActionListener() { Line 57-60
61 Repeat process for JTextField
Repeat process for
minuteField minuteField
Page 96
62 public void actionPerformed( ActionEvent event ) Outline
63 {
64 time.setMinute( TimeTestWindow.j
65 Integer.parseInt( event.getActionCommand() ) );
66 minuteField.setText( "" ); ava
67 displayTime();
68 } Logic differs from logic in
Line 64-67
69
70 } // end anonymous inner class
actionPerformed method of Logic differs from logic
71 hourField’s inner class in action-
72 ); // end call to addActionListener Performed method
73
74 container.add( minuteLabel ); of hourField’s inner
75 container.add( minuteField ); class
76
77 secondLabel = new JLabel( "Set Second" );
78 secondField = new JTextField( 10 ); Line 80-83
79 Repeat process for
80 secondField.addActionListener( Repeat process for JTextField
JTextField
81
82 // anonymous inner class
secondField secondField
83 new ActionListener() {
84
85 public void actionPerformed( ActionEvent event )
Line 87-90
86 { Logic differs from logic
87 time.setSecond( in action-
88 Integer.parseInt( event.getActionCommand() ) );
89 secondField.setText( "" );
Performed methods
90 displayTime(); of other inner classes
91 } Logic differs from logic in
92
93 } // end anonymous inner class
actionPerformed methods of
94 other inner classes
95 ); // end call to addActionListener
96 Page 97
97 container.add( secondLabel ); Outline
98 container.add( secondField );
99 TimeTestWindow.j
100 displayField = new JTextField( 30 );
101 displayField.setEditable( false ); ava
102 container.add( displayField );
103 }
Line 118-131
104
105 // display time in displayField Define anonymous
106 public void displayTime() inner class that extends
107 { WindowsAdapter to
108 displayField.setText( "The time is: " + time );
109 } enable closing of
110 JFrame
111 // create TimeTestWindow, register for its window events
112 // and display it to begin application's execution
113 public static void main( String args[] )
114 {
115 TimeTestWindow window = new TimeTestWindow(); Define anonymous inner class that
116
117 // register listener for windowClosing event
extends WindowsAdapter to
118 window.addWindowListener( enable closing of JFrame
119
120 // anonymous inner class for windowClosing event
121 new WindowAdapter() {
122
123 // terminate application when user closes window
124 public void windowClosing( WindowEvent event )
125 {
126 System.exit( 0 );
127 }
128
129 } // end anonymous inner class
130
131 ); // end call to addWindowListener Page 98
132 Outline
133 window.setSize( 400, 120 );
134 window.setVisible( true ); TimeTestWindow.j
135 }
136 ava
137 } // end class TimeTestWindow
Page 99
Outline
TimeTestWindow.j
ava
Page 100
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 names have the file name
OuterClassName$InnerClassName.class
• Anonymous inner class have the file name OuterClassName$#.class where #
starts at 1 and is incremented for each additional anonymous inner class
– Inner classes with class names can be defined as
• public, protected, private or package access
– Access outer class’ this reference OuterClassName.this
– When an anonymous inner class implements an interface, the class must
define every method in the interface
• There are 7 different methods that must be defined in every class that
implements WindowListener. We only need one (windowClosing). Java
provides an adapter class that already implements all the methods of the
interface. We extend the adapter class and override just the methods we need
to change.
2002 Prentice Hall. All rights reserved. Page 101
9.22 Type-Wrapper Classes for Primitive
Types
• Type-wrapper class
– Each primitive type has one
• Character, Byte, Integer, Boolean, etc.
• Numeric types inherit from class Number
– Enable to represent and manipulate primitive as objects of
class Object
• Primitive data types can be processed polymorphically
– Declared as final
– Many methods are declared static
{frozen} indicates
Elev ator Flo or constant (final in Java)
- m oving : Bo olean = false
- sum moned : Boo lea n = false + g etButto n( ) : Button
- c urrent Flo or : Integ er + g etDo or( ) : Door Concrete classes
- d estina tionFloor : Inte ger implement abstract
- tra velTim e : Int ege r = 5
+ ride( ) : v oid Concrete classesmethods
implement
+ req uestEleva to r( ) : void
+ enterElev ator( ) : v oid
abstract methods
+ exitElev ator( ) : v oid
+ dep art Ele vator( ) : void
+ getButton( ) : Button
+ getDoo r( ) : Door
Creates
1
1 2
Light ElevatorModel Floor
2 1
Turns
on/off
1 1
1 Resets
ElevatorShaft
1
1
2 2
Doo r Button
0..*
- op en : Boolea n = fa lse Signals - pressed : Boolean = false Presses
arrival Person
+ o penDoo r( ) : vo id + resetButton( ) : void 1 1
+ c lo seDoor( ) : v oid + pressButton( ) : void 1
1 1
1 Signals to Occupies
Opens 1 move
Elevator
Closes 1 Resets
1 1
Location
Rings - locationName : String
2 - capacity : Integer = 1 {frozen}
# setLocationName( String ) : void 1
+ getLocationName( ) : String
1 + getCapacity( ) : Integer
Bell
+ getButton( ) : Button
+ getDoor( ) : Door
• 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)
// class constructor
public Elevator() {}
}
• We also introduce
– Concurrent design patterns
• Used in multithreaded systems
• Chapter 15
– Architectural patterns
• Specify how subsystems interact with each other
• Chapter 17
• 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
Page 123
1 // SingletonExample.java Outline
2 // Attempt to create two Singleton objects
3 package com.deitel.jhtp4.designpatterns; SingletonExample
4
5 public class SingletonExample { .java
6
7 // run SingletonExample
8 public static void main( String args[] )
Line 14
9 { Create Singleton
10 Singleton firstSingleton; Create Singleton instance
instance
11 Singleton secondSingleton;
12
13 // create Singleton objects Line 15
14 firstSingleton = Singleton.getSingletonInstance(); Get same Singleton
15 secondSingleton = Singleton.getSingletonInstance();
16
instance
17 // the "two" Singletons should refer to same Singleton
18 if ( firstSingleton == secondSingleton )
19 System.out.println( "firstSingleton and " +
20 "secondSingleton refer to the same Singleton " +
21 "object" );
22 }
23 }
Get same Singleton instance
Page 124
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
• 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
• 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?
• 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