900 likes | 915 Views
This outline provides an introduction to object-oriented programming, superclasses and subclasses, protected members, the relationship between superclass and subclass objects, constructors and finalizers in subclasses, and more.
E N D
Object-Oriented Programming Outline 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
Chapter 9 - Object-Oriented Programming Outlinefinal Methods and ClassesAbstract Superclasses and Concrete ClassesPolymorphism ExamplesCase Study: A Payroll System Using PolymorphismNew Classes and Dynamic BindingCase Study: Inheriting Interface and ImplementationCase Study: Creating and Using InterfacesInner Class DefinitionsNotes on Inner Class DefinitionsType-Wrapper Classes for Primitive Types
Introduction • Object-Oriented Programming (OOP) • Inheritance - form of software reusability • New classes created from existing ones • Absorb attributes and behaivors, and add in their own • Override methods - redefine inherited methods • Subclass inherits from superclass • Direct superclass - subclass explicitly inherits • Indirect superclass - subclass inherits from two or more levels up the class heirarchy • Polymorphism • Write programs in a general fashion to handle a wide variety of classes • Abstraction - seeing the big picture
Introduction • Object-Oriented Programming • Introduce protected member access • Relationships • "is a" - inheritance • Object of subclass "is a" object of the superclass • "has a" - composition • Object "has a" object of another class as a member • Class libraries • New classes can inherit from them • Someday software may be constructed from standardized, reusable components (like hardware) • Create more powerful software
Superclasses and Subclasses • Inheritance example • A rectangle "is a" quadrilateral • Rectangle is a specific type of quadrilateral • Quadrilateral is the superclass, rectangle is the subclass • Incorrect to say quadrilateral "is a" rectangle • Naming can be confusing because subclass has more features than superclass • Subclass more specific than superclass • Every subclass "is an" object of its superclass, but not vice-versa • Form tree-like hierarchal structures • Create a hierarchy for class Shape (next slide)
Shape TwoDimensionalShape ThreeDimensionalShape Circle Square Triangle Sphere Cube Tetrahedron Superclasses and Subclasses • Using inheritance • Use keyword extends class TwoDimensionalShape extends Shape{ ... } • private members of superclass not directly accessible to subclass • All other variables keep their member access
protected Members • In a superclass • public members • Accessible anywhere program has a reference to a superclass or subclass type • private members • Accesible only in methods of the superclass • protected members • Intermediate protection between private and public • Only accessible by methods of superclass, of subclass, or classes in the same package • Subclass methods • Can refer to public or protected members by name • Overridden methods accessible with super.methodName
The following table shows the access to members permitted by each modifier: Modifiers
Relationship between Superclass Objects and Subclass Objects • Object of subclass • Can be treated as object of superclass • Reverse not true • Suppose many classes inherit from one superclass • Can make an array of superclass references • Treat all objects like superclass objects • Explicit cast • Convert superclass reference to a subclass reference (downcasting) • Can only be done when superclass reference actually referring to a subclass object • instanceof operator • if (p instanceof Circle) • Returns true if the object to which p points "is a" Circle
Relationship between Superclass Objects and Subclass Objects • Overridding methods • Subclass can redefine superclass methods • When method mentioned in subclass, subclass version used • Access original superclass method with super.methodName • To invoke superclass constructor explicitly • super(); //can pass arguments if needed • If called explicitly, must be first statement • Every Applet has used these techniques • We have overridden init and paint when we extended Japplet • Java implicitly uses class Object as superclass for all classes
4 public class Point { 41 public class Circle extends Point { // inherits from Point 8 public Point() 54 super( a, b ); // call to superclass constructor Relationship between Superclass Objects and Subclass Objects • Upcoming example • Every class implicitly inheirts from class Object • Every constructor must call superclass constructor • Called implicitly by default • If explicit, must be first command • Inherits from Point • Explicitly calls superclass (Point) constructor • Must be first statement in Circle constructor • To call default superclass construcor, use super()
83 Point pointRef, p; 84 Circle circleRef, c; 88 c = new Circle( 2.7, 120, 89 ); 95 pointRef = c; // assign Circle to pointRef 98 pointRef.toString(); Relationship between Superclass Objects and Subclass Objects • Both Point and Circle override toString • To call class Point's toString in class Circle • super.toString() • pointRef points to a Circle object • Allowed, because Circle "is a" Point • pointRef knows it is pointing to a Circle object • Calls the proper toString method • Example of polymorphism - more later
113 if ( p instanceof Circle ) { 87 p = new Point( 30, 50 ); 102 circleRef = (Circle) pointRef; Relationship between Superclass Objects and Subclass Objects • pointRef is pointing to a Circle • Downcast it to a Circle reference, assign to circleRef (explicit cast) • Operator instanceof • Returns true if object to which p points "is a" Circle • In this case, returns false
1 // Fig. 9.4: Point.java 2 // Definition of class Point 3 Notice the default (no argument) constructor. Implicit call to superclass constructor. Point implicitly inherits from class Object 4public class Point { 5 protected int x, y; // coordinates of the Point 6 7 // No-argument constructor 8 public Point() 9 { 10 // implicit call to superclass constructor occurs here 11 setPoint( 0, 0 ); 12 } 13 14 // Constructor 15 public Point( int a, int b ) 16 { 17 // implicit call to superclass constructor occurs here 18 setPoint( a, b ); 19 } 20 21 // Set x and y coordinates of Point 22 public void setPoint( int a, int b ) 23 { 24 x = a; 25 y = b; 26 } 27 28 // get x coordinate 29 public int getX() { return x; } 1. Point definition 1.1 Data members 1.2 Constructors 1.3 Methods
50 34 // convert the point into a String representation 38 // Fig. 9.4: Circle.java 51 // Constructor 39 // Definition of class Circle 35 public String toString() Class Point's method toString overrides the original toString in class Object 36 { return "[" + x + ", " + y + "]"; } 52 public Circle( double r, int a, int b ) 40 41 public class Circle extends Point { // inherits from Point 53 { 37 } 42 protected double radius; 54 super( a, b ); // call to superclass constructor Point constructor called implicitly Point constructor called explicitly, and must be the first statement in the subclass constructor 55 setRadius( r ); 43 56 } 44 // No-argument constructor 57 45 public Circle() 58 // Set radius of Circle 46 { 47 // implicit call to superclass constructor occurs here 59 public void setRadius( double r ) 48 setRadius( 0 ); 60 { radius = ( r >= 0.0 ? r : 0.0 ); } 49 } 30 31 // get y coordinate 32 public int getY() { return y; } 33 1.4 Overridden toString method ---------------- 1. Circle Definition 1.1 extends Point 1.2 Multiple constructors
67 68 // convert the Circle to a String 69 public String toString() 70 { 71 return "Center = " + "[" + x + ", " + y + "]" + 72 "; Radius = " + radius; 73 } 74 } 61 62 // Get radius of Circle 63 public double getRadius() { return radius; } 64 65 // Calculate area of Circle 66 public double area() { return Math.PI * radius * radius; } 1.3 Overridden toString method
75 // Fig. 9.4: Test.java 76 // Demonstrating the "is a" relationship 77 import java.text.DecimalFormat; 78 import javax.swing.JOptionPane; 79 80 public class InheritanceTest { 81 public static void main( String args[] ) Allowed because a subclass object "is a" superclass object 82 { The computer knows that pointRef is actually pointing to a Circle object, so it calls method toString of class Circle. This is an example of polymorphism, more later. 83 Point pointRef, p; 84 Circle circleRef, c; 85 String output; 86 87 p = new Point( 30, 50 ); 88 c = new Circle( 2.7, 120, 89 ); 89 90 output = "Point p: " + p.toString() + 91 "\nCircle c: " + c.toString(); 92 93 // use the "is a" relationship to refer to a Circle 94 // with a Point reference 95 pointRef = c; // assign Circle to pointRef 96 97 output += "\n\nCircle c (via pointRef): " + 98 pointRef.toString(); 1. Initialize objects 2. Refer to a subclass object with a superclass reference 2.1 toString
99 100 // Use downcasting (casting a superclass reference to a 101 // subclass data type) to assign pointRef to circleRef Downcast pointRef (which is really pointing to a Circle) to a Circle, and assign it to circleRef 102 circleRef = (Circle) pointRef; 103 Test if p (class Point) "is a" Circle. It is not. 104 output += "\n\nCircle c (via circleRef): " + 105 circleRef.toString(); 106 107 DecimalFormat precision2 = new DecimalFormat( "0.00" ); 108 output += "\nArea of c (via circleRef): " + 109 precision2.format( circleRef.area() ); 110 111 // Attempt to refer to Point object 112 // with Circle reference 113 if ( p instanceof Circle ) { 114 circleRef = (Circle) p; // line 40 in Test.java 115 output += "\n\ncast successful"; 116 } 117 else 118 output += "\n\np does not refer to a Circle"; 119 120 JOptionPane.showMessageDialog( null, output, 121 "Demonstrating the \"is a\" relationship", 122 JOptionPane.INFORMATION_MESSAGE ); 123 124 System.exit( 0 ); 125 } 126 } 2.2 Downcast 2.3 toString 2.4 area 3. if statement
23 protected void finalize() Constructors and Finalizers in Subclasses • Objects of subclass • Superclass constructor should be called • Initialize superclass variables • Default constructor called implicitly • Explicit call (using super) must first command • If methodfinalize defined • Subclass finalize should call superclass finalize as last action • Should be protected • Only subclasses have access
1 // Fig. 9.5: Point.java 2 // Definition of class Point 3 public class Point extends Object { 4 protected int x, y; // coordinates of the Point 5 6 // no-argument constructor 7 public Point() Only subclass may access protected methods. 8 { 9 x = 0; 10 y = 0; 11 System.out.println( "Point constructor: " + this ); 12 } 13 14 // constructor 15 public Point( int a, int b ) 16 { 17 x = a; 18 y = b; 19 System.out.println( "Point constructor: " + this ); 20 } 21 22 // finalizer 23 protected void finalize() 24 { 25 System.out.println( "Point finalizer: " + this ); 26 } 27 28 // convert the point into a String representation 29 public String toString() 30 { return "[" + x + ", " + y + "]"; } 31 } 1. Class Point 1.1 Constructors 1.2 Finalizer (protected)
32 // Fig. 9.5: Circle.java 50 System.out.println( "Circle constructor: " + this ); 33 // Definition of class Circle 51 } 34 public class Circle extends Point { // inherits from Point 52 35 protected double radius; 53 // finalizer 54 protected void finalize() 36 37 // no-argument constructor 55 { 38 public Circle() 56 System.out.println( "Circle finalizer: " + this ); 57 super.finalize(); // call superclass finalize method 39 { Circle finalizer calls superclass finalizer (in Point). 40 // implicit call to superclass constructor here 58 } 59 41 radius = 0; 42 System.out.println( "Circle constructor: " + this ); 43 } 44 45 // Constructor 46 public Circle( double r, int a, int b ) 47 { 48 super( a, b ); // call the superclass constructor 49 radius = r; 1. Class Circle (extendsPoint) 1.1 Constructors 1.2 Finalizer
63 return "Center = " + super.toString() + 67 // Fig. 9.5: Test.java 64 "; Radius = " + radius; 68 // Demonstrate when superclass and subclass 65 } 69 // constructors and finalizers are called. 66 } 70 public class Test { 71 public static void main( String args[] ) 72 { Mark objects for garbage collection by setting them to null. 73 Circle circle1, circle2; 74 75 circle1 = new Circle( 4.5, 72, 29 ); 76 circle2 = new Circle( 10, 5, 5 ); Call garbage collector (static method gc of class System). 60 // convert the Circle to a String 77 61 public String toString() 78 circle1 = null; // mark for garbage collection 79 circle2 = null; // mark for garbage collection 62 { 80 81 System.gc(); // call the garbage collector 82 } 83 } 1. Class Test 2. main 2.1 Initialize objects 2.2 System.gc
Point constructor: Center = [72, 29]; Radius = 0.0 Circle constructor: Center = [72, 29]; Radius = 4.5 Point constructor: Center = [5, 5]; Radius = 0.0 Circle constructor: Center = [5, 5]; Radius = 10.0 Circle finalizer: Center = [72, 29]; Radius = 4.5 Point finalizer: Center = [72, 29]; Radius = 4.5 Circle finalizer: Center = [5, 5]; Radius = 10.0 Point finalizer: Center = [5, 5]; Radius = 10.0 Program Output
Implicit Subclass-Object-to-Superclass-Object Conversion • References to subclass objects • May be implicitly converted to superclass references • Makes sense - subclass contains members corresponding to those of superclass • Referring to a subclass object with a superclass reference • Allowed - a subclass object "is a" superclass object • Can only refer to superclass members • Referring to a superclass object with a subclass reference • Error • Must first be cast to a superclass reference • Need way to use superclass references but call subclass methods • Discussed later in the chapter
Composition vs. Inheritance • "is a" relationship • Inheritance • "has a" relationship • Composition, having other objects as members • Example Employee “is a” BirthDate; //Wrong! Employee “has a” Birthdate; //Composition
Case Study: Point, Circle, Cylinder • Inheritance example • Class Point • protected variables x, y • Methods: setPoint, getX, getY, toString • Class Circle (extends Point) • protected variable radius • Methods: setRadius, getRadius, area, override toString • Class Cylinder (extends Circle) • protected variable height • Methods: setHeight, getHeight, area (surface area), volume, override toString
1 // Fig. 9.6: Point.java 2 // Definition of class Point 3 package com.deitel.jhtp3.ch09; 4 5 public class Point { 6 protected int x, y; // coordinates of the Point 7 8 // no-argument constructor 9 public Point() { setPoint( 0, 0 ); } 10 11 // constructor 12 public Point( int a, int b ) { setPoint( a, b ); } 13 14 // Set x and y coordinates of Point 15 public void setPoint( int a, int b ) 16 { 17 x = a; 18 y = b; 19 } 20 21 // get x coordinate 22 public int getX() { return x; } 23 24 // get y coordinate 25 public int getY() { return y; } 26 27 // convert the point into a String representation 28 public String toString() 29 { return "[" + x + ", " + y + "]"; } 30 } 1. Class Point 1.1 Instance variables 2. Constructors 2.1 Methods
15 // Constructor 1 // Fig. 9.7: Circle.java 2 // Definition of class Circle 16 public Circle( double r, int a, int b ) 3 package com.deitel.jhtp3.ch09; 17 { 4 18 super( a, b ); // call the superclass constructor 19 setRadius( r ); 5 public class Circle extends Point { // inherits from Point 20 } 6 protected double radius; 7 21 8 // no-argument constructor 22 // Set radius of Circle 23 public void setRadius( double r ) 9 public Circle() 10 { 24 { radius = ( r >= 0.0 ? r : 0.0 ); } 25 11 // implicit call to superclass constructor 12 setRadius( 0 ); 26 // Get radius of Circle 27 public double getRadius() { return radius; } 13 } 14 28 29 // Calculate area of Circle 30 public double area() 31 { return Math.PI * radius * radius; } 1. Class Circle (extends Point) 1.1 Instance variable 2. Constructors 2.1 Methods
34 public String toString() 35 { 36 return "Center = " + super.toString() + 37 "; Radius = " + radius; 38 } 39 } 32 33 // convert the Circle to a String 2.1 Methods
1 // Fig. 9.8: Cylinder.java 2 // Definition of class Cylinder 3 package com.deitel.jhtp3.ch09; 4 5 public class Cylinder extends Circle { 6 protected double height; // height of Cylinder 7 8 // No-argument constructor 9 public Cylinder() 10 { 11 // implicit call to superclass constructor here 12 setHeight( 0 ); 13 } 14 15 // constructor 16 public Cylinder( double h, double r, int a, int b ) 17 { 18 super( r, a, b ); 19 setHeight( h ); 20 } 21 22 // Set height of Cylinder 23 public void setHeight( double h ) 24 { height = ( h >= 0 ? h : 0 ); } 25 26 // Get height of Cylinder 27 public double getHeight() { return height; } 28 1. Class Cylinder (extends Circle) 1.1 Instance variable 2. Constructors 2.1 Methods
33 2 * Math.PI * radius * height; 45 // Fig. 9.8: Test.java 50 34 } 46 // Application to test class Cylinder 51 public class Test { 47 import javax.swing.JOptionPane; 52 public static void main( String args[] ) 35 53 { 36 // Calculate volume of Cylinder 48 import java.text.DecimalFormat; 54 Cylinder c = new Cylinder( 5.7, 2.5, 12, 23 ); 37 public double volume() { return super.area() * height; } 49 import com.deitel.jhtp3.ch09.Cylinder; 38 55 DecimalFormat precision2 = new DecimalFormat( "0.00" ); 39 // Convert the Cylinder to a String 56 String output; 40 public String toString() 57 41 { 42 return super.toString() + "; Height = " + height; 43 } 44 } 29 // Calculate area of Cylinder (i.e., surface area) 30 public double area() 31 { 32 return 2 * super.area() + 2.1 Methods ------------ 1. Class Test 2. main 2.1 Initialize object
63 c.setHeight( 10 ); 64 c.setRadius( 4.25 ); 65 c.setPoint( 2, 2 ); 66 67 output += 68 "\n\nThe new location, radius " + 69 "and height of c are\n" + c + 70 "\nArea is " + precision2.format( c.area() ) + 58 output = "X coordinate is " + c.getX() + 71 "\nVolume is " + precision2.format( c.volume() ); 72 59 "\nY coordinate is " + c.getY() + 60 "\nRadius is " + c.getRadius() + 73 JOptionPane.showMessageDialog( null, output, 74 "Demonstrating Class Cylinder", 61 "\nHeight is " + c.getHeight(); 62 75 JOptionPane.INFORMATION_MESSAGE ); 76 System.exit( 0 ); 77 } 78 } 2.2 Method calls 2.3 Set methods 2.4 Display changes 2.5 area and volume
Introduction to Polymorphism • With polymorphism • Write extensible programs • Generically process superclass objects • Easy to add classes to heirarchy • Little or no modification required • Only parts of program that need direct knowledge of new class must be changed
Type Fields and switch Statements • switch statements • Can be used to deal with many objects of different types • Appropriate action based on type • Problems • Programmer may forget to include a type • Might forget to test all possible cases • Every addition/deletion of a class requires all switch statements to be changed • Tracking all these changes is time consuming and error prone • Polymorphic programming can eliminate the need for switch logic • Avoids all these problems automatically
Dynamic Method Binding • Dynamic Method Binding • At execution time, method calls routed to appropriate version • Method called for appropriate class • Example • Triangle, Circle, and Square all subclasses of Shape • Each has an overridden draw method • Call draw using superclass references • At execution time, program determines to which class the reference is actually pointing • Calls appropriate draw method
final Methods and Classes • Declaring variables final • Indicates they cannot be modified after declaration • Must be initialized when declared • Declaring methods final • Cannot be overridden in a subclass • static and private methods are implicitly final • Program can inline final methods • Actually inserts method code at method call locations • Improves program performance • Declaring classes final • Cannot be a superclass (cannot inherit from it) • All methods in class are implicitly final
Abstract Superclasses and Concrete Classes • Abstract classes (abstract superclasses) • Sole purpose is to be a superclass • Other classes inherit from it • Cannot instantiate objects of an abstract class • Can still have instance variables and constructors • Too generic to define real objects • Declare class with keyword abstract • Concrete class • Can instantiate objects • Provide specifics • Class heirarchies • Most general classes are usually abstract • TwoDimensionalShape - too generic to be concrete
Polymorphism Examples • Class Quadrilateral • Rectangle "is a" Quadrilateral • getPerimeter method can be performed on any subclass • Square, Parallelogram, Trapezoid • Same method takes on "many forms" - polymorphism • Have an array of superclass references • Array would point to all the objects • Call getPerimeter using the references • Appropriate method called for each class • Adding a new subclass • Simply need to define getPerimeter for that class • Can refer to it with superclass reference
Polymorphism Examples • With polymorphism • New classes can be added easily • One method call can cause different actions to occur, depending on object receiving call • References • Can create references to abstract classes • Cannot instantiate objects of abstract classes • abstract methods • Keyword abstract • Any class with an abstract method must be abstract • abstract methods must be overridden in subclass • Otherwise, subclass must be abstract
Case Study: A Payroll System Using Polymorphism • Example program • abstract superclass Employee • abstract method earnings • Must be implemented in each subclass • Classes Boss, CommissionWorker, and PieceWorker, HourlyWorker • Override methods toString and earnings • Class Test • Initialize objects • Use an Employee reference and call toString and earnings • Through polymorphism, the appropriate class method is called
1 // Fig. 9.9: Employee.java 2 // Abstract base class Employee 3 Class Employee declared abstract, so no Employee objects can be created. Employee can still have a constructor, used by its derived classes. 4public abstract class Employee { 5 private String firstName; 6 private String lastName; 7 8 // Constructor abstract methods must be defined in concrete subclasses. 9 public Employee( String first, String last ) 10 { 11 firstName = first; 12 lastName = last; 13 } 14 15 // Return the first name 16 public String getFirstName() { return firstName; } 17 18 // Return the last name 19 public String getLastName() { return lastName; } 20 21 public String toString() 22 { return firstName + ' ' + lastName; } 23 24 // Abstract method that must be implemented for each 25 // derived class of Employee from which objects 26 // are instantiated. 27 public abstract double earnings(); 28 } 1. Class Employee (abstract base class) 1.1 Instance variables 1.2 Methods 1.3 earnings (abstract method)
29 // Fig. 9.9: Boss.java 30 // Boss class derived from Employee 31 32 public final class Boss extends Employee { 33 private double weeklySalary; 34 Implementing earnings is required because it was declared abstract and Boss is a concrete class. 35 // Constructor for class Boss 36 public Boss( String first, String last, double s) 37 { 38 super( first, last ); // call superclass constructor 39 setWeeklySalary( s ); 40 } 41 42 // Set the Boss's salary 43 public void setWeeklySalary( double s ) 44 { weeklySalary = ( s > 0 ? s : 0 ); } 45 46 // Get the Boss's pay 47 public double earnings() { return weeklySalary; } 48 49 // Print the Boss's name 50 public String toString() 51 { 52 return "Boss: " + super.toString(); 53 } 54 } 1. Class Boss (extendsEmployee) 1.1 Instance variable 1.2 Define earnings (required) 1.3 Override toString
77 // Set CommissionWorker's commission 55 // Fig. 9.9: CommissionWorker.java 56 // CommissionWorker class derived from Employee 78 public void setCommission( double c ) 57 79 { commission = ( c > 0 ? c : 0 ); } 58 public final class CommissionWorker extends Employee { 80 59 private double salary; // base salary per week 81 // Set CommissionWorker's quantity sold 60 private double commission; // amount per item sold 82 public void setQuantity( int q ) 61 private int quantity; // total items sold for week 83 { quantity = ( q > 0 ? q : 0 ); } 62 84 63 // Constructor for class CommissionWorker 64 public CommissionWorker( String first, String last, 65 double s, double c, int q) 66 { 67 super( first, last ); // call superclass constructor 68 setSalary( s ); 69 setCommission( c ); 70 setQuantity( q ); 71 } 72 73 // Set CommissionWorker's weekly base salary 74 public void setSalary( double s ) 75 { salary = ( s > 0 ? s : 0 ); } 76 1. Class CommissionWorker (extendsEmployee) 1.1 Instance variables 1.2 Constructor
86 public double earnings() 95 // Fig. 9.9: PieceWorker.java 87 { return salary + commission * quantity; } 96 // PieceWorker class derived from Employee 97 88 98 public final class PieceWorker extends Employee { 89 // Print the CommissionWorker's name 99 private double wagePerPiece; // wage per piece output 90 public String toString() 91 { 100 private int quantity; // output for week 92 return "Commission worker: " + super.toString(); 101 102 // Constructor for class PieceWorker 93 } 85 // Determine CommissionWorker's earnings 94 } 103 public PieceWorker( String first, String last, 104 double w, int q ) 105 { 106 super( first, last ); // call superclass constructor 107 setWage( w ); 108 setQuantity( q ); 109 } 110 111 // Set the wage 112 public void setWage( double w ) 113 { wagePerPiece = ( w > 0 ? w : 0 ); } 114 1.3 Define earnings (required) 1.4 Override toString ----------------- 1. Class PieceWorker (extendsEmployee) 1.1 Constructor
128 // Fig. 9.9: HourlyWorker.java 115 // Set the number of items output 116 public void setQuantity( int q ) 129 // Definition of class HourlyWorker 117 { quantity = ( q > 0 ? q : 0 ); } 130 131 public final class HourlyWorker extends Employee { 118 119 // Determine the PieceWorker's earnings 132 private double wage; // wage per hour 133 private double hours; // hours worked for week 120 public double earnings() 121 { return quantity * wagePerPiece; } 134 122 135 // Constructor for class HourlyWorker 123 public String toString() 136 public HourlyWorker( String first, String last, 137 double w, double h ) 124 { 138 { 125 return "Piece worker: " + super.toString(); 139 super( first, last ); // call superclass constructor 126 } 127 } 140 setWage( w ); 141 setHours( h ); 142 } 143 1.2 Define earnings (required) 1.3 Override toString ---------------- 1. Class HourlyWorker (extendsEmployee) 1.1 Constructor
146 { wage = ( w > 0 ? w : 0 ); } 160 // Fig. 9.9: Test.java 147 161 // Driver for Employee hierarchy 162 import javax.swing.JOptionPane; 148 // Set the hours worked 163 import java.text.DecimalFormat; 149 public void setHours( double h ) 150 { hours = ( h >= 0 && h < 168 ? h : 0 ); } 164 165 public class Test { 151 152 // Get the HourlyWorker's pay 166 public static void main( String args[] ) References to abstract classes are allowed. 167 { 153 public double earnings() { return wage * hours; } 154 168 Employee ref; // superclass reference 155 public String toString() 169 String output = ""; 156 { 170 157 return "Hourly worker: " + super.toString(); 158 } 159 } 144 // Set the wage 145 public void setWage( double w ) 1.2 Define earnings (required) 1.3 Override toString ----------------------- 1. Class Test 1.1 Employee reference
176 new PieceWorker( "Bob", "Lewis", 2.5, 200 ); 177 HourlyWorker h = Employee reference ref points to Boss object. Through polymorphism, the appropriate Boss versions of toString and earnings are called. To check, they are called through the Boss object as well. 178 new HourlyWorker( "Karen", "Price", 13.75, 40 ); 179 180 DecimalFormat precision2 = new DecimalFormat( "0.00" ); 181 182 ref = b; // Employee reference to a Boss 183 output += ref.toString() + " earned $" + 184 precision2.format( ref.earnings() ) + "\n" + 185 b.toString() + " earned $" + 186 precision2.format( b.earnings() ) + "\n"; 171 Boss b = new Boss( "John", "Smith", 800.00 ); 187 188 ref = c; // Employee reference to a CommissionWorker 172 CommissionWorker c = 173 new CommissionWorker( "Sue", "Jones", 189 output += ref.toString() + " earned $" + 174 400.0, 3.0, 150); 190 precision2.format( ref.earnings() ) + "\n" + 175 PieceWorker p = 191 c.toString() + " earned $" + 192 precision2.format( c.earnings() ) + "\n"; 193 194 ref = p; // Employee reference to a PieceWorker 195 output += ref.toString() + " earned $" + 196 precision2.format( ref.earnings() ) + "\n" + 197 p.toString() + " earned $" + 198 precision2.format( p.earnings() ) + "\n"; 199 1.2 Initialize subclass objects 2. Method calls through Employee reference
207 "Demonstrating Polymorphism", 208 JOptionPane.INFORMATION_MESSAGE ); 209 System.exit( 0 ); 210 } 211 } 200 ref = h; // Employee reference to an HourlyWorker 201 output += ref.toString() + " earned $" + 202 precision2.format( ref.earnings() ) + "\n" + 203 h.toString() + " earned $" + 204 precision2.format( h.earnings() ) + "\n"; 205 206 JOptionPane.showMessageDialog( null, output, 2. Method calls through Employee reference Program Output