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
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
Composition
Has a relationship
Superclass
Subclasses
GraduateStudent UndergraduateStudent Circle Triangle Rectangle CarLoan HomeImprovementLoan MortgageLoan FacultyMember StaffMember CheckingAccount SavingsAccount
Fig. 9.2 An inheritance hierarchy for university CommunityMembers. CommunityMember is a direct superclass of Employee
C o m m u n i t y M e m b e r
CommunityMember is an indirect superclass of Faculty
E m p l o y e e F a c u l t y
S t u d e n t S t a f f
A l u m n i
A d m i n i s t r a t o r
T e a c h e r
S h a p e T w o D i m e n s i o n a l S h a p e C i r c l e S q u a r e T r i a n g l e T h r e e D i m e n s i o n a l S h a p e S p h e r e C u b e T e t r a h e d r o n
9.3
protected Members
Accessed only by
Superclass methods Subclass methods Methods of classes in same package package access
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
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)
Point.java Line 5 protected members prevent clients from direct access (unless 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 = } x and y coordinates of Point void setPoint( int xCoordinate, int yCoordinate ) xCoordinate; yCoordinate;
34 35 36 37 38 39 40 41 42 43 44 45 46
// get y coordinate public int getY() { return y; } // convert into a String representation public String toString() { return "[" + x + ", " + y + "]"; } } // end class Point
Outline
Point.java
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;
Outline
Circle.java Line 4 Circle is a Point subclass
// no-argument constructor protected variables and public public Circle() { methods (except for constructor) // implicit call to superclass constructor occurs here setRadius( 0 ); }
Line 4 Implicit call to Point constructor Circle inherits // constructor public Circle( double circleRadius, int xCoordinate, Points protected int yCoordinate ) variables and public { // call superclass constructor to set coordinates methods (except for super( xCoordinate, yCoordinate ); constuctor)
// set radius setRadius( circleRadius ); }
// set radius of Circle public void setRadius( double circleRadius ) { radius = ( circleRadius >= 0.0 ? circleRadius : 0.0 ); }
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
// get radius of Circle public double getRadius() { return radius; } // calculate area of Circle public double area() { return Math.PI * radius * radius; }
Outline
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
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; // Java extension packages import javax.swing.JOptionPane;
Outline
InheritanceTest. java
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() + Superclass object can Line 29 reference subclass object // use "is a" relationship to refer to a Circle Point invokes // with a Point reference Circles toString point2 = circle1; // assigns Circle to a Point reference Point still invokes Circle methods 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. "\nCircle circle1: " + circle1.toString();
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
// 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
Constructors
class Point {
protected int x, y; public Point() {} public Point(int xx, int yy) {
x = xx; y = yy;
} Point p = new Point(10, 10); Circle c1 = new Circle(); Circle c2 = new Circle(10, 10); // erorr
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
Outline
Point.java Lines 7-20 Superclass constructors
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 ); } // 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
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
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 Line 9 Implicit call to Point constructor
// no-argument constructor public Circle() { // implicit call to superclass constructor here radius = 0; System.out.println( "Circle constructor: " + this ); }
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 Points radius = circleRadius; method finalize, System.out.println( "Circle constructor: " + this ); } but call it using super Override Points method // finalizer finalize, but call it using super protected void finalize()
{
System.out.println( "Circle finalizer: " + this ); super.finalize(); // call superclass finalize method }
32 33 34 35 36 37 38 39
// convert the Circle to a String public String toString() { return "Center = " + super.toString() + "; Radius = " + radius; } } // end class Circle
Outline
Circle.java
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 Lines 10-11 Instantiate Circle objects Line 17 Invoke Circles method finalize by calling System.gc
// test when constructors and finalizers are called public static void main( String args[] ) { Circle circle1, circle2;
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
Composition
Has a relationship Employee has a TelephoneNumber
9.9
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)
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
// No-argument constructor public Point() { // implicit call to superclass constructor occurs here setPoint( 0, 0 ); } Constructor and overloaded // constructor public Point( int xCoordinate, int yCoordinate ) { // implicit call to superclass constructor occurs here setPoint( xCoordinate, yCoordinate ); } // set public { x = y = } x and y coordinates of Point void setPoint( int xCoordinate, int yCoordinate ) xCoordinate; yCoordinate;
constructor
35 36 37 38 39 40 41 42 43 44 45 46 47
// get y coordinate public int getY() { return y; } // convert into a String representation public String toString() { return "[" + x + ", " + y + "]"; } } // end class Point
Outline
Point.java
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.11: Test.java // Applet to test class Point // Java extension packages import javax.swing.JOptionPane; // Deitel packages import com.deitel.jhtp4.ch09.Point; public class Test { // 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 );
Outline
Test.java Line 15 Instantiate Point object Lines 18-19 Methods getX and getY read Points protected variables
// use implicit call to point.toString() output += "\n\nThe new location of point is " + point;
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
// no-argument constructor protected variables and public public Circle() methods (except for constuctor) { // implicit call to superclass constructor occurs here setRadius( 0 ); } // constructor public Circle( double int yCoordinate ) { // call superclass super( xCoordinate, yCoordinate ); // set radius setRadius( circleRadius ); }
Line 5 Circle inherits Implicit call to Point constructor Points protected circleRadius, int xCoordinate, variables and public methods (except for constructor to set coordinates constuctor) Line 11 Implicit call to Point constructor
// set radius of Circle public void setRadius( double circleRadius ) { radius = ( circleRadius >= 0.0 ? circleRadius : 0.0 ); }
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; } // 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
Outline
Circle.java
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.13: Test.java // Applet to test class Circle // Java core packages import java.text.DecimalFormat; // Java extension packages import javax.swing.JOptionPane; // Deitel packages import com.deitel.jhtp4.ch09.Circle; public class Test {
Outline
Test.java Line 19 Instantiate Circle object
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" ); Circles protected variables
// get coordinates and radius String output = "X coordinate is " + circle.getX() + "\nY coordinate is " + circle.getY() + "\nRadius is " + circle.getRadius();
Lines 23-24 and 29 Calls to methods getX, getY and setPoint read and manipulate Calls to methods getX, getY and Circles inherited setPoint read and manipulate Circles protected variables inherited protected variables
// 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() );
36 37 38 39 40 41 42 43
JOptionPane.showMessageDialog( null, output, "Demonstrating Class Circle", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } } // end class Test
Outline
Test.java
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
Cylinder.java
public class Cylinder extends Circle { protected double height; // height of Cylinder Cylinder
// no-argument constructor public Cylinder() { // implicit call to superclass constructor here setHeight( 0 ); }
inherits Points and Circles protected Line 5 Cylinder is a variables and public methods (except for constuctors) Circle subclass
Line 5 Implicit call to Circle constructor Cylinder inherits // constructor Points and public Cylinder( double cylinderHeight, double cylinderRadius, Circles 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 ); }
// 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
Outline
Override method area of class Circle
Cylinder.java Lines 39-43 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; } // 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
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.15: Test.java // Application to test class Cylinder // Java core packages import java.text.DecimalFormat; // Java extension packages import javax.swing.JOptionPane; // Deitel packages import com.deitel.jhtp4.ch09.Cylinder; public class Test {
Outline
Test.java Line 19 Instantiate Cylinder object Instantiate Cylinder object Lines 23-31 Method calls read and manipulate Cylinders protected variables and inherited protected variables
// 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" ); // 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 Cylinders 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() ); JOptionPane.showMessageDialog( null, output, "Demonstrating Class Cylinder", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } } // end class Test
Outline
Test.java
Error prone
Programmer can forget to make appropriate type test Adding and deleting switch statements
final class
Cannot be superclass (cannot be extended)
Class cannot inherit final classes
Concrete classes
Classes from which objects are instantiated Provide specifics for instantiating objects
Square, Circle and Triangle
Easily extensible
Suppose we add class Mercurian Class Mercurian inherits superclass GamePiece Overrides method drawYourself
9.16 Case Study: A Payroll System Using Polymorphism Abstract methods and polymorphism
Abstract superclass Employee
Method earnings applies to all employees Persons earnings dependent on type of Employee
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. public abstract class Employee { private String firstName; private String lastName;
Outline
// constructor public Employee( String first, { firstName = first; lastName = last; } // get first name public String getFirstName() { return firstName; } // get last name public String getLastName() { return lastName; }
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 data abstract class can have instance data and nonabstract methods for subclasses Lines 9-13 abstract class can have constructors for subclasses to initialize inherited data
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(); } // end class Employee
Outline
Employee.java Line 35 Subclasses must implement abstract method
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
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 Employees 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 ) Employees public methods (except for 0 ? salary : 0 ); constuctor) Required to implement Employees 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
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
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
an
Outline
CommissionWorker .java Line 4 CommissionWorker is an Employee subclass Line 13 Explicit call to Employee constructor using super
// 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 ); }
// set CommissionWorker's commission public void setCommission( double itemCommission ) { commission = ( itemCommission > 0 ? itemCommission : 0 ); }
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 ) implement Employees Required to { 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 Employees method earnings; this implementation differs from that in Boss
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); }
Outline
PieceWorker.java Line 4 PieceWorker is an Employee subclass Line 12 Explicit call to Employee constructor using super
Lines 30-33 Implementation of Employees method earnings; differs from that of Boss and CommissionWorker
Implementation of Employees 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(); } } // end class PieceWorker
Outline
PieceWorker.java
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
HourlyWorker.jav a Line 4 PieceWorker is an Employee subclass Line 12 Explicit call to Employee constructor using super
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 ); }
Line 31 Implementation of Employee s method Implementation of 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; }
33 34 35 36 37 38
public String toString() { return "Hourly worker: " + super.toString(); } } // end class HourlyWorker
Outline
HourlyWorker.jav a
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.21: Test.java // Driver for Employee hierarchy // Java core packages import java.text.DecimalFormat; // Java extension packages import javax.swing.JOptionPane; public class Test {
Outline
Test.java Line 15 Test cannot instantiate Employee Test cannot but can reference one instantiate Employee but can reference one Instantiate one instance each of Lines 18-28 EmployeeInstantiate subclassesone instance each of Employee subclasses
// test Employee hierarchy public static void main( String args[] ) { Employee employee; // superclass reference String output = "";
Boss boss = new Boss( "John", "Smith", 800.0 ); CommissionWorker commisionWorker = new CommissionWorker( "Sue", "Jones", 400.0, 3.0, 150 ); PieceWorker pieceWorker = new PieceWorker( "Bob", "Lewis", 2.5, 200 );
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
Outline
Test.java
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;
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 Lines 41-55 Do same for CommissionWorker and PieceWorker
output += employee.toString() + " earned $" + precision2.format( employee.earnings() ) + "\n" + pieceWorker.toString() + " earned $" + precision2.format( pieceWorker.earnings() ) + "\n";
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
// 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 ); System.exit( 0 ); } } // end class Test
Outline
Test.java Lines 58-63 Repeat for HourlyWorker
9.17 New Classes and Dynamic Binding Dynamic binding (late binding)
Objects type need not be know at compile time At run time, call is matched with method of called object
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
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 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; }
cannot be instantiated
Outline
Shape.java Line 4 Shape cannot be instantiated
Lines 7-16 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(); } // end class Shape
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
Point.java Line 4 Point inherits Shapes public methods Line 5 protected members prevent clients from direct access (unless clients are Point subclasses or are in same package)
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 = }
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
// get y coordinate public int getY() { return y; } // convert point into String representation public String toString() { return "[" + x + ", " + y + "]"; } Implementation // return shape name public String getName() { return "Point"; }
Outline
Point.java Lines 45-48 Implementation of Shapes method getName *** Note ***
Point does not override methods area and volume, because points have neither area nor volume
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;
Outline
Circle.java Line 4 Circle inherits variables/methods from Point and Shape
// no-argument constructor public Circle() { // implicit call to superclass constructor here setRadius( 0 ); } // 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; }
Lines 5 and 24-34 Methods for reading/setting protected value for reading/setting protected value
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 Shapes have volume) method getName
// return shape name public String getName() { return "Circle"; } } // end class Circle
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
public class Cylinder extends Circle { protected double height; // height of Cylinder
Cylinder inherits variables and methods from Point, Circle and Shape
Outline
Cylinder.java Line 4 Cylinder inherits variables and methods from Point, Circle and Shape
// no-argument constructor public Cylinder() { // 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 ); setHeight( cylinderHeight ); } // set height of Cylinder public void setHeight( double cylinderHeight ) { height = ( cylinderHeight >= 0 ? cylinderHeight : 0 ); }
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
// get height of Cylinder public double getHeight() { return height; } // 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; }
Outline
Cylinder.java Lines 38-47 Override methods area and volume Lines 56-59 Implementation of Shapes method getName
// convert Cylinder to a String representation public String toString() { return super.toString() + "; Height = " + height; }
// return shape name public String getName() { return "Cylinder"; } } // end class Cylinder
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.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 {
Outline
Test.java
// 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;
Lines 16-18 Instantiate one instance each of Shape subclasses Lines 21-30 Create three Shapes to reference each subclass object
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
Outline
Test.java
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// 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(); }
Outline
Classes that implement Shape must implement these methods
Shape.java Lines 7-13 Classes that implement Shape must implement these methods
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.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 ); }
Outline
Point.java
// constructor public Point( int xCoordinate, int yCoordinate ) { setPoint( xCoordinate, yCoordinate ); }
// Set public { x = y = }
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
// get y coordinate public int getY() { return y; } // convert point into String representation public String toString() { return "[" + x + ", " + y + "]"; } // calculate area public double area() { return 0.0; }
Outline
Point.java Lines 45-60 Implement methods specified by interface Shape
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.29: Circle.java // Definition of class Circle public class Circle extends Point { protected double radius; // inherits from Point
Outline
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 ); 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
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 Circle.java Lines 43-47 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"; } } // end class Circle
Override methods area and Lines 37-40 and 50-53 getName but not method volume Override methods area and getName but not method volume
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
Outline
Cylinder.java Line 4 Circle inherits variables/methods from Point and Circle and method implementations of Shape
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 ); 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; }
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() + "; } // return shape name public String getName() { return "Cylinder"; } } // end class Cylinder
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;
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; 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;
Outline
Test.java
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
Outline
Test.java Output is identical to that of Fig. 9.26
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.32: Time.java // Time class definition. // Java core packages import java.text.DecimalFormat; // 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
Outline
Time.java 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 ); }
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
// validate and set minute public void setMinute( int m ) { minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); } // validate and set second public void setSecond( int s ) { second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } // get hour public int getHour() { return hour; }
Outline
Time.java Mutator and accessor methods
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" );
Outline
Time.java Lines 67-76 Override method java.lang.Object .toString
}
} // end class Time
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.33: TimeTestWindow.java // Demonstrating the Time class set and get methods // Java core packages import java.awt.*; import java.awt.event.*; // Java extension packages import javax.swing.*;
Outline
TimeTestWindow.j ava Line 11 JFrame provides basic window attributes and behaviors
public class TimeTestWindow extends JFrame { private Time time; private JLabel hourLabel, minuteLabel, secondLabel; private JTextField hourField, minuteField, secondField, displayField; JFrame private JButton exitButton;
// set up GUI public TimeTestWindow() { super( "Inner Class Demonstration" ); time = new Time();
(unlike JApplet ) 19 Line has constructor JFrame (unlike JApplet) has Instantiate Time object constructor Line 23 Instantiate Time object Line 26 Instantiate object of inner-class that Instantiate object of innerimplements class that implements ActionListener ActionListener
2002 Prentice Hall.
All rights reserved.
// create an instance of inner class ActionEventHandler ActionEventHandler handler = new ActionEventHandler(); // set up GUI Container container = getContentPane(); container.setLayout( new FlowLayout() );
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
// end constructor
// display time in displayField public void displayTime() { displayField.setText( "The time is: " + time ); }
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
// create TimeTestWindow and display it public static void main( String args[] ) { TimeTestWindow window = new TimeTestWindow();
Outline
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 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 // user pressed Enter key in minuteField else if ( event.getSource() == minuteField ) { time.setMinute( Integer.parseInt( event.getActionCommand() ) ); minuteField.setText( "" ); }
actionLines depending 84-99 on where event Determine originated action depending on where event originated
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( "" ); } displayTime(); } } } // end inner class ActionEventHandler
Outline
TimeTestWindow.j ava
Outline
TimeTestWindow.j ava
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.*; // Java extension packages import javax.swing.*;
Outline
TimeTestWindow.j ava
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 );
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
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
Lines 38-44 ActionListener Inner class implements method Pass ActionListener as actionPerformed argument to GUI components method addActionListener Line 33 Pass Action); Listener to GUI components 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 } // end anonymous inner class
Outline
TimeTestWindow.j ava
); // end call
container.add( container.add(
actionPerformed method of Line 64-67 hourFields inner class Logic differs from logic to addActionListener in actionPerformed method minuteLabel ); of hourFields inner minuteField ); class Line 80-83 Repeat process for JTextField Repeat process for secondField JTextField secondField Line 87-90 Logic differs from logic in actionPerformed methods of other inner classes
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 } // end anonymous inner class
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
container.add( secondLabel ); container.add( secondField ); displayField = new JTextField( 30 ); displayField.setEditable( false ); container.add( displayField ); } // 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(
Outline
TimeTestWindow.j ava Line 118-131 Define anonymous inner class that extends WindowsAdapter to enable closing of JFrame
// terminate application when user closes window public void windowClosing( WindowEvent event ) { System.exit( 0 ); }
} // end anonymous inner class
Outline
TimeTestWindow.j ava
Outline
TimeTestWindow.j ava
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
Outer class is responsible for creating inner class objects Inner classes can be declared static
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
Fig. 9.37 Class diagram modeling generalization of superclass Location and subclasses Elevator and Floor. Pound sign (#) indicates protected member
Loc a tion
Outline
Italics indicate abstract class or method
- 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
Pound sign (#) {frozen} indicates indicates protected constant (final in Java) member {frozen} indicates constant (final in Java) Concrete classes implement abstract methods Concrete classes implement abstract methods
Elev ator - m oving : Bo olean = false - sum moned : Boo lea n = false - c urrentFlo or : Integ er - d estina tionFloor : Inte ger - tra velT im 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
1
1 2
1 ElevatorShaft 1 2 Button - pressed : Boolean = false + resetButton( ) : void + pressButton( ) : void 1 1 Resets
Signals arrival
1 Opens Closes 1 1
Elevator
1 1
Occupies
Rings
Bell
Location - locationName : String 2 - capacity : Integer = 1 {frozen} # setLocationName( String ) : void + getLocationName( ) : String + getCapacity( ) : Integer + getButton( ) : Button + getDoor( ) : Door
Fig. 9.39 Class diagram with attributes and operations (incorporating inheritance).
Eleva torM odel - numb erOfPe ople : Integ er = 0 + a dd Pe rson( ) : 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 + 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 velT im 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 + ringBell( ) : v oid Ele va torShaft Lig ht - lig htOn : Boo lea n = false + turnOnLig ht( ) : vo id + turnOffLig ht( ) : vo id
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; // class constructor public Elevator() {} // class methods public void ride() {} public void requestElevator() {} public void enterElevator() {} public void exitElevator() {} public void departElevator() {} // method overriding getButton public Button getButton() { return elevatorButton; } // method overriding getDoor public Door getDoor() { return elevatorDoor; } }
Outline
Step 2
Implement abstract classes
9.24 (Optional) Discovering Design Patterns: Introducing Creational, Structural and Behavioral Design Patterns Design-patterns discussion
Discuss each type
Creational Structural Behavioral
Architectural patterns
Specify how subsystems interact with each other Chapter 17
Se c tio n
9.24 13.18
17.11 21.12
Ja va Ho w to Pro g ra m 4/ e .
Sec tion
15.13
Single-Threaded Execution Guarded Suspension Balking Read/Write Lock Two-Phase Termination Model-View-Controller Layers
17.11
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 .
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
// Singleton.java // Demonstrates Singleton design pattern package com.deitel.jhtp4.designpatterns; public final class Singleton { // Singleton object returned by method getSingletonInstance private static Singleton singleton; private constructor
Outline
Singleton.java
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(); return singleton; } }
Lines 20-23 Instantiate Singleton object only once, but return same reference
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// SingletonExample.java // Attempt to create two Singleton objects package com.deitel.jhtp4.designpatterns; public class SingletonExample { // run SingletonExample public static void main( String args[] ) { Singleton firstSingleton; Singleton secondSingleton;
Outline
SingletonExample .java Line 14 Create Singleton instance Create Singleton instance Line 15 Get same 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" ); } }
Mid-term exam Xy dng lp Date Xy dng lp Time Date Xy dng lp FlightTicket - Day - Month TicketTest - Year
FlightTicket
+ Date() + Date(d,m,y) +getDay() +setDay(d) +getMonth() +setMonth(m) +getYear() +setYear(y)
Time
Hour Minute + Time() + Time(h,m) +getHour() +setHour(h) +getMinute() +setMinute(m)
- departureDate - departureTime - noOfTickets - price - totalPrice - typeOfCabin +getDepartureDate() +setDepartureDate( d, m, y) +getDepartureTime() +setDepartureTime(obj) +getTotalPrice() +displayTicketInformation()
2002 Prentice Hall. All rights reserved.
Instance variable to store the type of cabin. This variable will hold the value 1(Business class, pr*3), 2(First class, pr*2), or 3(Economy class).