Chapter 10 ObjectOriented Programming Polymorphism Outline 10 1
Chapter 10 - Object-Oriented Programming: Polymorphism Outline 10. 1 Introduction 10. 2 Relationships Among Objects in an Inheritance Hierarchy 10. 2. 1 Invoking Superclass Methods from Subclass Objects 10. 2. 2 Using Superclass References with Subclass-Type Variables 10. 2. 3 Subclass Method Calls via Superclass-Type Variables 10. 3 Polymorphism Examples 10. 4 Abstract Classes and Methods 10. 5 Case Study: Inheriting Interface and Implementation 10. 6 final Methods and Classes 10. 7 Case Study: Payroll System Using Polymorphism 10. 8 Case Study: Creating and Using Interfaces 期末考到此 10. 9 Nested Classes 10. 10 Type-Wrapper Classes for Primitive Types 2003 Prentice Hall, Inc. All rights reserved. 1
2 10. 1 Introduction • Polymorphism – “Program in the general” – Treat objects in same class hierarchy as if all superclass objects – Abstract class • Common functionality – Makes programs extensible • New classes added easily, can still be processed • In our examples – Use abstract superclass Shape • Defines common interface (functionality) • Point, Circle and Cylinder inherit from Shape – Class Employee for a natural example about earning 2003 Prentice Hall, Inc. All rights reserved.
10. 2 Relationships Among Objects in an Inheritance Hierarchy • Previously (Section 9. 4), – Circle inherited from Point – Manipulated Point and Circle objects using references to invoke methods • This section discusses – Invoking superclass methods from subclass objects – Using superclass references with subclass-type variables – Subclass method calls via superclass-type variables: an error • Key concept – subclass object can be treated as superclass object • “is-a” relationship • superclass object is not a subclass object 2003 Prentice Hall, Inc. All rights reserved. 3
10. 2. 1 Invoking Superclass Methods from Subclass Objects • Store references to superclass and subclass objects – Assign a superclass reference to superclass-type variable • straightforward – Assign a subclass reference to a subclass-type variable • straightforward – Assign a subclass reference to a superclass variable • “is a” relationship • For any non-static method call, the type of the variable used to call the method determines which methods can be called. • The type of the object to which the variable refers determines the actual methods used to respond to the method call. 2003 Prentice Hall, Inc. All rights reserved. 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // Fig. 10. 1: Hierarchy. Relationship. Test 1. java // Assigning superclass and subclass references to superclass- and // subclass-type variables. import javax. swing. JOption. Pane; Outline Hierarchy. Relation ship. Test 1. java public class Hierarchy. Relationship. Test 1 { public static void main( String[] args ) { // assign superclass reference to superclass-type variable Assign superclass Point 3 point = new Point 3( 30, 50 ); Line 11 Assign superclass reference to superclass-type variablereference to superclasstype variable // assign subclass reference to subclass-type variable Circle 4 circle = new Circle 4( 120, 89, 2. 7 ); Assign subclass reference to Line 14 subclass-type variable // invoke to. String on superclass object using superclass variable String output = "Call Point 3's to. String with superclass" + " reference to superclass object: n" + point. to. String(); // invoke to. String on subclass object using subclass variable output += "nn. Call Circle 4's to. String with subclass" + " reference to subclass object: n" + circle. to. String(); Assign subclass reference subclass-typeon variable Invoketoto. String superclass object using Line 17 superclass variable Invoke to. String on objectonusing Invokesuperclass to. String superclass variable subclass object using subclass variable Line 22 Invoke to. String on subclass object using subclass variable 2003 Prentice Hall, Inc. All rights reserved.
24 25 26 27 28 29 30 31 32 33 34 35 // invoke to. String on subclass object. Assign using subclass superclass variableto reference Point 3 point. Ref = circle; superclass-type variable output += "nn. Call Circle 4's to. String with superclass" + " reference to subclass object: n" + point. Ref. to. String(); JOption. Pane. show. Message. Dialog( null, output ); Outline Invoke to. String on subclass object using superclass variable // display output System. exit( 0 ); } // end main } // end class Hierarchy. Relationship. Test 1 Hierarchy. Relati onship. Test 1. jav a Line 25 Assign subclass reference to superclass -type variable. Line 27 Invoke to. String on subclass object using superclass variable. 2003 Prentice Hall, Inc. All rights reserved.
10. 2. 2 Using Superclass References with Subclass-Type Variables • Previous example – Assigned subclass reference to superclass-type variable • Circle “is a” Point • Assign superclass reference to subclass-type variable – Implicitly: Compiler error • No “is a” relationship • Point is not a Circle • Circle has data/methods that Point does not – set. Radius (declared in Circle) not declared in Point – Explicitly cast superclass references to subclass references • Called downcasting: OK if the object inside is indeed a subclass object • Invoke subclass functionality 2003 Prentice Hall, Inc. All rights reserved. 7
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // Fig. 10. 2: Hierarchy. Relationship. Test 2. java // Attempt to assign a superclass reference to a subclass-type variable. Outline public class Hierarchy. Relationship. Test 2 { public static void main( String[] args ) { Point 3 point = new Point 3( 30, 50 ); Circle 4 circle; // subclass-type variable // assign superclass reference to subclass-type variable circle = point; // Error: a Point 3 is not a Circle 4 } } // end class Hierarchy. Relationship. Test 2 Assigning superclass reference to subclass-type variable causes compiler error Hierarchy. Relationship. Test 2. java: 12: incompatible types found : Point 3 required: Circle 4 circle = point; // Error: a Point 3 is not a Circle 4 ^ 1 error Hierarchy. Relati onship. Test 2. jav a Line 12 Assigning superclass reference to subclasstype variable causes compiler error. 2003 Prentice Hall, Inc. All rights reserved.
10. 2. 3 Subclass Method Calls via Superclass -Type variables • Call a subclass method with superclass reference – Compiler error • Subclass methods are not superclass methods 2003 Prentice Hall, Inc. All rights reserved. 9
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // Fig. 10. 3: Hierarchy. Relationship. Test 3. java // Attempting to invoke subclass-only member methods through // a superclass reference. Outline public class Hierarchy. Relationship. Test 3 { public static void main( String[] args ) { Point 3 point; Circle 4 circle = new Circle 4( 120, 89, 2. 7 ); point = circle; // aim superclass reference at subclass object // invoke superclass (Point 3) methods on subclass // (Circle 4) object through superclass reference int x = point. get. X(); int y = point. get. Y(); point. set. X( 10 ); point. set. Y( 20 ); point. to. String(); Hierarchy. Relati onship. Test 3. jav a 2003 Prentice Hall, Inc. All rights reserved.
22 23 24 25 26 27 28 29 30 31 32 // attempt to invoke subclass-only (Circle 4) methods on // subclass object through superclass (Point 3) reference double radius = point. get. Radius(); point. set. Radius( 33. 33 ); double diameter = point. get. Diameter(); double circumference = point. get. Circumference(); double area = point. get. Area(); } // end main } // end class Hierarchy. Relationship. Test 3 Attempt to invoke subclassonly (Circle 4) methods on subclass object through superclass (Point 3) reference. Outline Hierarchy. Relati onship. Test 3. jav a Lines 24 -28 Attempt to invoke subclass-only (Circle 4) methods on subclass object through superclass (Point 3) reference. 2003 Prentice Hall, Inc. All rights reserved.
Hierarchy. Relationship. Test 3. java: 24: cannot resolve symbol : method get. Radius () location: class Point 3 double radius = point. get. Radius(); ^ Hierarchy. Relationship. Test 3. java: 25: cannot resolve symbol : method set. Radius (double) location: class Point 3 point. set. Radius( 33. 33 ); ^ Hierarchy. Relationship. Test 3. java: 26: cannot resolve symbol : method get. Diameter () location: class Point 3 double diameter = point. get. Diameter(); ^ Hierarchy. Relationship. Test 3. java: 27: cannot resolve symbol : method get. Circumference () location: class Point 3 double circumference = point. get. Circumference(); ^ Hierarchy. Relationship. Test 3. java: 28: cannot resolve symbol : method get. Area () location: class Point 3 double area = point. get. Area(); ^ 5 errors Outline Hierarchy. Relati onship. Test 3. jav a 2003 Prentice Hall, Inc. All rights reserved.
10. 2 Relationships Among Objects in an Inheritance Hierarchy • Summary – Assign a superclass reference to superclass-type variable • straightforward – Assign a subclass reference to a subclass-type variable • straightforward – Assign a subclass reference to a superclass variable is safe • “is a” relationship • This reference can be used to invoke only superclass methods. – Assign a superclass reference to a subclass variable is a compiler error. • To avoid this error, explicit casting is required. • At execution time, if the object to which the reference refers is not a subclass object, an exception will occur. 2003 Prentice Hall, Inc. All rights reserved. 13
14 10. 3 Polymorphism Examples • Example 1 – Suppose Rectangle derives from Quadrilateral • Rectangle more specific than Quadrilateral • Any operation on Quadrilateral can be done on Rectangle (i. e. , perimeter, area) • Example 2: Suppose designing video game – Superclass Space. Object • Subclasses Martian, Space. Ship, Laser. Beam • Contains method draw – To refresh screen • Send draw message to each object • Same message has “many forms” of results 2003 Prentice Hall, Inc. All rights reserved.
15 10. 3 Polymorphism Examples • Video game example, continued – Easy to add class Mercurian • Extends Space. Object • Provides its own implementation of draw – Programmer does not need to change code • Calls draw regardless of object’s type • Mercurian objects “plug right in” 2003 Prentice Hall, Inc. All rights reserved.
16 10. 4 Abstract Classes and Methods • Abstract classes – Are superclasses (called abstract superclasses) with abstract methods – Cannot be instantiated – Incomplete • Concrete subclasses must fill in "missing pieces" • Concrete classes – Can be instantiated – Implement every method they declare – Provide specifics 2003 Prentice Hall, Inc. All rights reserved.
17 10. 4 Abstract Classes and Methods (Cont. ) • An inheritance hierarchy is not required to contain abstract classes. • However, class hierarchies headed by abstract superclasses often are used to reduce client code’s dependencies on specific subclass types. • Example: Fig 9. 3 p 403 2003 Prentice Hall, Inc. All rights reserved.
18 Shape Two. Dimensional. Shape Circle Square Triangle 2003 Prentice Hall, Inc. All rights reserved. Three. Dimensional. Shape Sphere Cube Tetrahedron
19 10. 4 Abstract Classes and Methods (Cont. ) • To make a class abstract – Declare with keyword abstract – Contain one or more abstract methods public abstract void draw(); – Abstract methods • No implementation, must be overridden 2003 Prentice Hall, Inc. All rights reserved.
20 10. 4 Abstract Classes and Methods (Cont. ) • Application example – Abstract class Shape • Declares draw as abstract method – Circle, Triangle, Rectangle extends Shape • Each must implement draw – Each object can draw itself • Iterators – Array, Array. List (Chapter 22) – Walk through list elements – Used in polymorphic programming to traverse a collection 2003 Prentice Hall, Inc. All rights reserved.
10. 5 Case Study: Inheriting Interface and Implementation • Make abstract superclass Shape – Abstract method (must be implemented) • get. Name, to. String • Default implementation does not make sense – Methods may be overridden • get. Area, get. Volume – Default implementations return 0. 0 • If not overridden, uses superclass default implementation – Subclasses Point, Circle, Cylinder 2003 Prentice Hall, Inc. All rights reserved. 21
10. 5 Case Study: Inheriting Interface and Implementation Shape Point Circle Cylinder Fig. 10. 4 Shape hierarchy class diagram. 2003 Prentice Hall, Inc. All rights reserved. 22
10. 5 Case Study: Inheriting Interface and Implementation get. Area get. Volume get. Name to. String Shape 0. 0 abstract Default Object implementatio n Point 0. 0 "Point" [x, y] πr 2 0. 0 "Circle" center=[x, y]; radius=r 2πr 2 +2πrh πr 2 h "Cylinder" center=[x, y]; radius=r; height=h Circle Cylinder Fig. 10. 5 Polimorphic interface for the Shape hierarchy classes. 2003 Prentice Hall, Inc. All rights reserved. 23
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 Outline // Fig. 10. 6: Shape. java // Shape abstract-superclass declaration. public abstract class Shape extends Object { // return area of shape; 0. 0 by default public double get. Area() Keyword abstract { declares class Shape as return 0. 0; abstract class } // return volume of shape; 0. 0 by default public double get. Volume() { return 0. 0; } // abstract method, overridden by subclasses public abstract String get. Name(); } // end abstract class Shape. java Line 4 Keyword abstract declares class Shape as abstract class Line 19 Keyword abstract declares method get. Name as abstract method 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // Fig. 10. 7: Point. java // Point class declaration inherits from Shape. Outline public class Point extends Shape { private int x; // x part of coordinate pair private int y; // y part of coordinate pair // no-argument constructor; x and y default to 0 public Point() { // implicit call to Object constructor occurs here } // constructor public Point( int x. Value, int y. Value ) { // implicit call to Object constructor occurs here x = x. Value; // no need for validation y = y. Value; // no need for validation } Point. java // set x in coordinate pair public void set. X( int x. Value ) { x = x. Value; // no need for validation } 2003 Prentice Hall, Inc. All rights reserved.
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 // return x from coordinate pair public int get. X() { return x; } Outline // set y in coordinate pair public void set. Y( int y. Value ) { y = y. Value; // no need for validation } // return y from coordinate pair public int get. Y() { return y; } Override abstract method get. Name. // override abstract method get. Name to return "Point" public String get. Name() { return "Point"; } Point. java Lines 47 -50 Override abstract method get. Name. // override to. String to return String representation of Point public String to. String() { return "[" + get. X() + ", " + get. Y() + "]"; } } // end class Point 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 10. 8: Circle. java // Circle class inherits from Point. Outline public class Circle extends Point { private double radius; // Circle's radius // no-argument constructor; radius defaults to 0. 0 public Circle() { // implicit call to Point constructor occurs here } // constructor public Circle( int x, int y, double radius. Value ) { super( x, y ); // call Point constructor set. Radius( radius. Value ); } Circle. java // set radius public void set. Radius( double radius. Value ) { radius = ( radius. Value < 0. 0 ? 0. 0 : radius. Value ); } 2003 Prentice Hall, Inc. All rights reserved.
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 // return radius public double get. Radius() { return radius; } Outline // calculate and return diameter public double get. Diameter() { return 2 * get. Radius(); } // calculate and return circumference Override method public double get. Circumference() get. Area to return { circle area return Math. PI * get. Diameter(); } Circle. java Lines 45 -48 Override method get. Area to return circle area. // override method get. Area to return Circle area public double get. Area() { return Math. PI * get. Radius(); } 2003 Prentice Hall, Inc. All rights reserved.
50 51 52 53 54 55 56 57 58 59 60 61 62 // override abstract method get. Name to return "Circle" public String get. Name() Override { return "Circle"; abstract } method get. Name Outline // override to. String to return String representation of Circle public String to. String() { return "Center = " + super. to. String() + "; Radius = " + get. Radius(); } } // end class Circle. java Lines 51 -54 Override abstract method get. Name. 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 10. 9: Cylinder. java // Cylinder class inherits from Circle. Outline public class Cylinder extends Circle { private double height; // Cylinder's height // no-argument constructor; height defaults to 0. 0 public Cylinder() { // implicit call to Circle constructor occurs here } // constructor public Cylinder( int x, int y, double radius, double height. Value ) { super( x, y, radius ); // call Circle constructor set. Height( height. Value ); } Cylinder. java // set Cylinder's height public void set. Height( double height. Value ) { height = ( height. Value < 0. 0 ? 0. 0 : height. Value ); } 2003 Prentice Hall, Inc. All rights reserved.
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 // get Cylinder's height public double get. Height() { return height; } Override method get. Area to return cylinder area // override abstract method get. Area to Override return Cylinder method area public double get. Area() get. Volume to { return cylinder return 2 * super. get. Area() + get. Circumference() * get. Height(); volume } Outline Cylinder. java Lines 33 -36 Override method get. Area to return cylinder area // override abstract method get. Volume to return Cylinder volume public double get. Volume() { return super. get. Area() * get. Height(); } Lines 39 -42 Override method get. Volume to return cylinder volume // override abstract method get. Name to return "Cylinder" public String get. Name() Override { abstract return "Cylinder"; method get. Name } Lines 45 -48 Override abstract method get. Name 2003 Prentice Hall, Inc. All rights reserved.
49 50 51 52 53 54 55 56 Outline // override to. String to return String representation of Cylinder public String to. String() { return super. to. String() + "; Height = " + get. Height(); } } // end class Cylinder. java 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Fig. 10: Abstract. Inheritance. Test. java // Driver for shape, point, circle, cylinder hierarchy. import java. text. Decimal. Format; import javax. swing. JOption. Pane; Outline public class Abstract. Inheritance. Test { public static void main( String args[] ) { // set floating-point number format Decimal. Format two. Digits = new Decimal. Format( "0. 00" ); // create Point, Circle and Cylinder objects Point point = new Point( 7, 11 ); Circle circle = new Circle( 22, 8, 3. 5 ); Cylinder cylinder = new Cylinder( 20, 3. 3, 10. 75 ); Abstract. Inherit ance. Test. java // obtain name and string representation of each object String output = point. get. Name() + ": " + point + "n" + circle. get. Name() + ": " + circle + "n" + cylinder. get. Name() + ": " + cylinder + "n"; Shape array. Of. Shapes[] = new Shape[ 3 ]; // create Shape array 2003 Prentice Hall, Inc. All rights reserved.
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 // aim array. Of. Shapes[ 0 ] at subclass Point object array. Of. Shapes[ 0 ] = point; Outline // aim array. Of. Shapes[ 1 ] at subclass Circle. Create objectan array. Of. Shapes[ 1 ] = circle; array of Loop through generic Shape objects array. Of. Shapes to get // aim array. Of. Shapes[ 2 ] at subclass Cylinder object name, string representation, array. Of. Shapes[ 2 ] = cylinder; Abstract. Inherit area and volume of every ance. Test. java shape in array // loop through array. Of. Shapes to get name, string // representation, area and volume of every Shape in array for ( int i = 0; i < array. Of. Shapes. length; i++ ) { output += "nn" + array. Of. Shapes[ i ]. get. Name() + ": " + array. Of. Shapes[ i ]. to. String() + "n. Area = " + two. Digits. format( array. Of. Shapes[ i ]. get. Area() ) + "n. Volume = " + two. Digits. format( array. Of. Shapes[ i ]. get. Volume() ); } JOption. Pane. show. Message. Dialog( null, output ); System. exit( 0 ); } // end main // display output Lines 26 -32 Create an array of generic Shape objects Lines 36 -42 Loop through array. Of. Shapes to get name, string representation, area and volume of every shape in array } // end class Abstract. Inheritance. Test 2003 Prentice Hall, Inc. All rights reserved.
35 2003 Prentice Hall, Inc. All rights reserved.
36 10. 6 final Methods and Classes • final methods – Cannot be overridden – private methods are implicitly final – static methods are implicitly final • final classes – Cannot be superclasses – Methods in final classes are implicitly final – e. g. , class String 2003 Prentice Hall, Inc. All rights reserved.
10. 7 Case Study: Payroll System Using Polymorphism • Create a payroll program – Use abstract methods and polymorphism • Problem statement – 4 types of employees, paid weekly • • Salaried (fixed salary, no matter the hours) Hourly (overtime [>40 hours] pays time and a half) Commission (paid percentage of sales) Base-plus-commission (base salary + percentage of sales) – Boss wants to raise pay by 10% 2003 Prentice Hall, Inc. All rights reserved. 37
10. 9 Case Study: Payroll System Using Polymorphism • Superclass Employee – Abstract method earnings (returns pay) • abstract because need to know employee type • Cannot calculate for generic employee – Other classes extend Employee Salaried. Employee Commission. Employee Base. Plus. Commission. Employee 2003 Prentice Hall, Inc. All rights reserved. Hourly. Employee 38
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Outline // Fig. 10. 12: Employee. java // Employee abstract superclass. public abstract class Employee { private String first. Name; private String last. Name; private String social. Security. Number; Declares class Employee as abstract class. // constructor public Employee( String first, String last, String ssn ) { first. Name = first; last. Name = last; social. Security. Number = ssn; } // set first name public void set. First. Name( String first ) { first. Name = first; } Employee. java Line 4 Declares class Employee as abstract class. 2003 Prentice Hall, Inc. All rights reserved.
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 // return first name public String get. First. Name() { return first. Name; } Outline // set last name public void set. Last. Name( String last ) { last. Name = last; } // return last name public String get. Last. Name() { return last. Name; } Employee. java // set social security number public void set. Social. Security. Number( String number ) { social. Security. Number = number; // should validate } 2003 Prentice Hall, Inc. All rights reserved.
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 Outline // return social security number public String get. Social. Security. Number() { return social. Security. Number; } // return String representation of Employee object public String to. String() { return get. First. Name() + " " + get. Last. Name() + "nsocial security number: " + get. Social. Security. Number(); } Employee. java // abstract method overridden by subclasses public abstract double earnings(); } // end abstract class Employee Abstract method overridden by subclasses Line 61 Abstract method overridden by subclasses. 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 10. 13: Salaried. Employee. java // Salaried. Employee class extends Employee. Outline public class Salaried. Employee extends Employee { private double weekly. Salary; // constructor Use superclass public Salaried. Employee( String first, String last, basic fields. String social. Security. Number, double salary ) { super( first, last, social. Security. Number ); set. Weekly. Salary( salary ); } // set salaried employee's salary public void set. Weekly. Salary( double salary ) { weekly. Salary = salary < 0. 0 ? 0. 0 : salary; } constructor for Salaried. Employe e. java Line 11 Use superclass constructor for basic fields. // return salaried employee's salary public double get. Weekly. Salary() { return weekly. Salary; } 2003 Prentice Hall, Inc. All rights reserved.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 // calculate salaried employee's pay; // override abstract method earnings in Employee public double earnings() { return get. Weekly. Salary(); } Must implement abstract Outline method earnings. // return String representation of Salaried. Employee object public String to. String() { return "nsalaried employee: " + super. to. String(); } Salaried. Employe e. java } // end class Salaried. Employee Lines 29 -32 Must implement abstract method earnings. 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // Fig. 10. 14: Hourly. Employee. java // Hourly. Employee class extends Employee. Outline public class Hourly. Employee extends Employee { private double wage; // wage per hour private double hours; // hours worked for week // constructor public Hourly. Employee( String first, String last, String social. Security. Number, double hourly. Wage, double hours. Worked ) { super( first, last, social. Security. Number ); set. Wage( hourly. Wage ); set. Hours( hours. Worked ); } // set hourly employee's wage public void set. Wage( double wage. Amount ) { wage = wage. Amount < 0. 0 ? 0. 0 : wage. Amount; } Hourly. Employee. java // return wage public double get. Wage() { return wage; } 2003 Prentice Hall, Inc. All rights reserved.
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 // set hourly employee's hours worked public void set. Hours( double hours. Worked ) { hours = ( hours. Worked >= 0. 0 && hours. Worked <= 168. 0 ) ? hours. Worked : 0. 0; } Outline // return hours worked public double get. Hours() { return hours; } // calculate hourly employee's pay; // override abstract method earnings in Employee public double earnings() Must implement abstract { method earnings. if ( hours <= 40 ) // no overtime return wage * hours; else return 40 * wage + ( hours - 40 ) * wage * 1. 5; } Hourly. Employee. java Lines 44 -50 Must implement abstract method earnings. // return String representation of Hourly. Employee object public String to. String() { return "nhourly employee: " + super. to. String(); } } // end class Hourly. Employee 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // Fig. 10. 15: Commission. Employee. java // Commission. Employee class extends Employee. Outline public class Commission. Employee extends Employee { private double gross. Sales; // gross weekly sales private double commission. Rate; // commission percentage // constructor public Commission. Employee( String first, String last, String social. Security. Number, double gross. Weekly. Sales, double percent ) { super( first, last, social. Security. Number ); set. Gross. Sales( gross. Weekly. Sales ); set. Commission. Rate( percent ); } Commission. Emplo yee. java // set commission employee's rate public void set. Commission. Rate( double rate ) { commission. Rate = ( rate > 0. 0 && rate < 1. 0 ) ? rate : 0. 0; } // return commission employee's rate public double get. Commission. Rate() { return commission. Rate; } 2003 Prentice Hall, Inc. All rights reserved.
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 // set commission employee's weekly base salary public void set. Gross. Sales( double sales ) { gross. Sales = sales < 0. 0 ? 0. 0 : sales; } Outline // return commission employee's gross sales amount public double get. Gross. Sales() { return gross. Sales; } // calculate commission employee's Must pay; implement abstract // override abstract method earnings in Employee method earnings. public double earnings() { return get. Commission. Rate() * get. Gross. Sales(); } Commission. Emplo yee. java Lines 44 -47 Must implement abstract method earnings. // return String representation of Commission. Employee object public String to. String() { return "ncommission employee: " + super. to. String(); } } // end class Commission. Employee 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // Fig. 10. 16: Base. Plus. Commission. Employee. java // Base. Plus. Commission. Employee class extends Commission. Employee. Outline public class Base. Plus. Commission. Employee extends Commission. Employee { private double base. Salary; // base salary per week // constructor public Base. Plus. Commission. Employee( String first, String last, String social. Security. Number, double gross. Sales. Amount, double rate, double base. Salary. Amount ) { super( first, last, social. Security. Number, gross. Sales. Amount, rate ); set. Base. Salary( base. Salary. Amount ); } // set base-salaried commission employee's base salary public void set. Base. Salary( double salary ) { base. Salary = salary < 0. 0 ? 0. 0 : salary; } Base. Plus. Commiss ion. Employee. jav a // return base-salaried commission employee's base salary public double get. Base. Salary() { return base. Salary; } 2003 Prentice Hall, Inc. All rights reserved.
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 // calculate base-salaried commission employee's earnings; // override method earnings in Commission. Employee public double earnings() Override method earnings { in Commission. Employee return get. Base. Salary() + super. earnings(); } // return String representation of Base. Plus. Commission. Employee public String to. String() { return "nbase-salaried commission employee: " + super. get. First. Name() + " " + super. get. Last. Name() + "nsocial security number: " + super. get. Social. Security. Number(); } } // end class Base. Plus. Commission. Employee Outline Base. Plus. Commiss ion. Employee. jav a Lines 30 -33 Override method earnings in Commission. Emplo yee 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 10. 17: Payroll. System. Test. java // Employee hierarchy test program. import java. text. Decimal. Format; import javax. swing. JOption. Pane; Outline public class Payroll. System. Test { public static void main( String[] args ) { Decimal. Format two. Digits = new Decimal. Format( "0. 00" ); // create Employee array Employee employees[] = new Employee[ 4 ]; // initialize array with Employees employees[ 0 ] = new Salaried. Employee( "John", "Smith", "111 -11 -1111", 800. 00 ); employees[ 1 ] = new Commission. Employee( "Sue", "Jones", "222 -22 -2222", 10000, . 06 ); employees[ 2 ] = new Base. Plus. Commission. Employee( "Bob", "Lewis", "333 -33 -3333", 5000, . 04, 300 ); employees[ 3 ] = new Hourly. Employee( "Karen", "Price", "444 -44 -4444", 16. 75, 40 ); Payroll. System. Te st. java String output = ""; 2003 Prentice Hall, Inc. All rights reserved.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 // generically process each element in array employees for ( int i = 0; i < employees. length; i++ ) { output += employees[ i ]. to. String(); Outline // determine whether element is a Base. Plus. Commission. Employee if ( employees[ i ] instanceof Base. Plus. Commission. Employee ) { Determine whether element is a Payroll. System. Te Base. Plus. Commission. Empl downcast Employee reference to st. java oyee Base. Plus. Commission. Employee reference // // Base. Plus. Commission. Employee current. Employee = ( Base. Plus. Commission. Employee ) employees[ i ]; double output Line 32 Downcast Employee reference to Determine whether Base. Plus. Commission. Employee element is a old. Base. Salary = current. Employee. get. Base. Salary(); += "nold base salary: reference $" + old. Base. Salary; Base. Plus. Commiss ion. Employee current. Employee. set. Base. Salary( 1. 10 * old. Base. Salary ); output += "nnew base salary with 10% increase is: $" + current. Employee. get. Base. Salary(); } // end if output += "nearned $" + employees[ i ]. earnings() + "n"; Line 37 Downcast Employee reference to Base. Plus. Commiss ion. Employee reference } // end for 2003 Prentice Hall, Inc. All rights reserved.
52 53 54 55 56 57 58 59 60 61 62 // get type name of each object in employees array for ( int j = 0; j < employees. length; j++ ) output += "n. Employee " + j + " is a " + employees[ j ]. get. Class(). get. Name(); JOption. Pane. show. Message. Dialog( null, output ); System. exit( 0 ); Outline Get type name of each object in employees // display output array } // end main } // end class Payroll. System. Test Payroll. System. Te st. java Lines 53 -55 Get type name of each object in employees array 2003 Prentice Hall, Inc. All rights reserved.
10. 8 Case Study: Creating and Using Interfaces • Use interface Shape – Replace abstract class Shape • Interface – Declaration begins with interface keyword – Classes implement an interface (and its methods) – Contains public abstract methods • Classes (that implement the interface) must implement these methods 2003 Prentice Hall, Inc. All rights reserved. 53
1 2 3 4 5 6 7 8 9 // Fig. 10. 18: Shape. java // Shape interface declaration. public interface public double public String Shape { get. Area(); get. Volume(); get. Name(); Classes that implement Shape must implement these methods Outline // calculate area // calculate volume // return shape name } // end interface Shape. java Lines 5 -7 Classes that implement Shape must implement these methods 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // Fig. 10. 19: Point. java // Point class declaration implements interface Shape. Outline public class Point extends Object implements Shape { private int x; // x part of coordinate pair private int y; // y part of coordinate pair // no-argument constructor; x and y default to 0 Point implements public Point() { // implicit call to Object constructor occurs here } // constructor public Point( int x. Value, int y. Value ) { // implicit call to Object constructor occurs here x = x. Value; // no need for validation y = y. Value; // no need for validation } interface Shape Point. java Line 4 Point implements interface Shape // set x in coordinate pair public void set. X( int x. Value ) { x = x. Value; // no need for validation } 2003 Prentice Hall, Inc. All rights reserved.
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 // return x from coordinate pair public int get. X() { return x; } Outline // set y in coordinate pair public void set. Y( int y. Value ) { y = y. Value; // no need for validation } // return y from coordinate pair public int get. Y() { return y; } Point. java 2003 Prentice Hall, Inc. All rights reserved.
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 // declare abstract method get. Area public double get. Area() { return 0. 0; } // declare abstract method get. Volume public double get. Volume() { return 0. 0; } Outline Implement methods specified by interface Shape // override abstract method get. Name to return "Point" public String get. Name() { return "Point"; } // override to. String to return String representation of Point public String to. String() { return "[" + get. X() + ", " + get. Y() + "]"; } Point. java Lines 47 -59 Implement methods specified by interface Shape } // end class Point 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Fig. 10. 20: Interface. Test. java // Test Point, Circle, Cylinder hierarchy with interface Shape. import java. text. Decimal. Format; import javax. swing. JOption. Pane; Outline public class Interface. Test { public static void main( String args[] ) { // set floating-point number format Decimal. Format two. Digits = new Decimal. Format( "0. 00" ); // create Point, Circle and Cylinder objects Point point = new Point( 7, 11 ); Circle circle = new Circle( 22, 8, 3. 5 ); Cylinder cylinder = new Cylinder( 20, 3. 3, 10. 75 ); Interface. Test. j ava Line 23 Create Shape array // obtain name and string representation of each object String output = point. get. Name() + ": " + point + "n" + Create Shape array circle. get. Name() + ": " + circle + "n" + cylinder. get. Name() + ": " + cylinder + "n"; Shape array. Of. Shapes[] = new Shape[ 3 ]; // create Shape array 2003 Prentice Hall, Inc. All rights reserved.
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 Outline // aim array. Of. Shapes[ 0 ] at subclass Point object array. Of. Shapes[ 0 ] = point; // aim array. Of. Shapes[ 1 ] at subclass Circle object array. Of. Shapes[ 1 ] = circle; // aim array. Of. Shapes[ 2 ] at subclass array. Of. Shapes[ 2 ] = cylinder; Loop through array. Of. Shapes to Cylinder get name, object string representation, area and volume of every shape in array // loop through array. Of. Shapes to get name, string // representation, area and volume of every Shape in array for ( int i = 0; i < array. Of. Shapes. length; i++ ) { output += "nn" + array. Of. Shapes[ i ]. get. Name() + ": " + array. Of. Shapes[ i ]. to. String() + "n. Area = " + two. Digits. format( array. Of. Shapes[ i ]. get. Area() ) + "n. Volume = " + two. Digits. format( array. Of. Shapes[ i ]. get. Volume() ); } JOption. Pane. show. Message. Dialog( null, output ); System. exit( 0 ); // display output Interface. Test. j ava Lines 36 -42 Loop through array. Of. Shapes to get name, string representation, area and volume of every shape in array. } // end main } // end class Interface. Test 2003 Prentice Hall, Inc. All rights reserved.
Outline Interface. Test. j ava 2003 Prentice Hall, Inc. All rights reserved.
10. 8 Case Study: Creating and Using Interfaces (Cont. ) • Implementing Multiple Interface – Provide common-separated list of interface names after keyword implements • Declaring Constants with Interfaces – public interface public static } 2003 Prentice Hall, Inc. All rights reserved. Constants final int { ONE = 1; TWO = 2; THREE = 3; 61
62 10. 9 Nested Classes • Top-level classes – Not declared inside a class or a method • Nested classes – Declared inside other classes – Inner classes • Non-static nested classes 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 10. 21: Time. java // Time class declaration with set and get methods. import java. text. Decimal. Format; public class Time { private int hour; private int minute; private int second; Outline // 0 - 23 // 0 - 59 // one formatting object to share in to. String and to. Universal. String private static Decimal. Format two. Digits = new Decimal. Format( "00" ); // Time constructor initializes each instance variable to zero; // ensures that Time object starts in a consistent state public Time() { this( 0, 0, 0 ); // invoke Time constructor with three arguments } Time. java // Time constructor: hour supplied, minute and second defaulted to 0 public Time( int h ) { this( h, 0, 0 ); // invoke Time constructor with three arguments } 2003 Prentice Hall, Inc. All rights reserved.
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 // Time constructor: hour and minute supplied, second defaulted to 0 public Time( int h, int m ) { this( h, m, 0 ); // invoke Time constructor with three arguments } Outline // Time constructor: hour, minute and second supplied public Time( int h, int m, int s ) { set. Time( h, m, s ); } // Time constructor: another Time 3 object supplied public Time( Time time ) { // invoke Time constructor with three arguments this( time. get. Hour(), time. get. Minute(), time. get. Second() ); } Time. java // Set Methods // set a new time value using universal time; perform // validity checks on data; set invalid values to zero public void set. Time( int h, int m, int s ) { set. Hour( h ); // set the hour set. Minute( m ); // set the minute set. Second( s ); // set the second } 2003 Prentice Hall, Inc. All rights reserved.
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 // validate and set hour public void set. Hour( int h ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); } Outline // validate and set minute public void set. Minute( int m ) { minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); } // validate and set second public void set. Second( int s ) { second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } Time. java // Get Methods // get hour value public int get. Hour() { return hour; } 2003 Prentice Hall, Inc. All rights reserved.
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 // get minute value public int get. Minute() { return minute; } Outline // get second value public int get. Second() { return second; } // convert to String in universal-time format Override method public String to. Universal. String() { java. lang. Object. to. String return two. Digits. format( get. Hour() ) + ": " + two. Digits. format( get. Minute() ) + ": " + two. Digits. format( get. Second() ); } // convert to String in standard-time format public String to. String() { return ( ( get. Hour() == 12 || get. Hour() == 0 ) ? 12 : get. Hour() % 12 ) + ": " + two. Digits. format( get. Minute() ) + ": " + two. Digits. format( get. Second() ) + ( get. Hour() < 12 ? " AM" : " PM" ); } Time. java Lines 101 -107 Override method java. lang. Objec t. to. String } // end class Time 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // Fig. 10. 22: Time. Test. Window. java JFrame provides basic window // Inner class declarations used to create event handlers. attributes and behaviors import java. awt. *; import java. awt. event. *; import javax. swing. *; Outline public class Time. Test. Window extends JFrame { private Time time; private JLabel hour. Label, minute. Label, second. Label; private JText. Field hour. Field, minute. Field, second. Field, display. Field; private JButton exit. Button; // set up GUI public Time. Test. Window() { // call JFrame constructor to set title bar string Instantiate Time object super( "Inner Class Demonstration" ); time = new Time(); Line 7 JFrame provides JFrame (unlike JApplet) basic window has constructor attributes and behaviors // create Time object // use inherited method get. Content. Pane to get window's content pane Container container = get. Content. Pane(); container. set. Layout( new Flow. Layout() ); // change layout // set up hour. Label and hour. Field hour. Label = new JLabel( "Set Hour" ); hour. Field = new JText. Field( 10 ); container. add( hour. Label ); container. add( hour. Field ); Time. Test. Window. java Line 17 JFrame (unlike JApplet) has constructor Line 19 Instantiate Time object 2003 Prentice Hall, Inc. All rights reserved.
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 Outline // set up minute. Label and minute. Field minute. Label = new JLabel( "Set Minute" ); minute. Field = new JText. Field( 10 ); container. add( minute. Label ); container. add( minute. Field ); // set up second. Label and second. Field second. Label = new JLabel( "Set Second" ); second. Field = new JText. Field( 10 ); container. add( second. Label ); container. add( second. Field ); // set up display. Field = new JText. Field( 30 ); display. Field. set. Editable( false ); container. add( display. Field ); // set up exit. Button = new JButton( "Exit" ); container. add( exit. Button ); Time. Test. Window. java Line 53 Instantiate object of inner-class that implements Action. Listener. // create an instance of inner class Action. Event. Handler handler = new Action. Event. Handler(); 2003 Prentice Hall, Inc. All rights reserved.
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 // register event handlers; the object referenced by handler // is the Action. Listener, which contains method action. Performed // that will be called to handle action events generated by // hour. Field, minute. Field, second. Field and exit. Button hour. Field. add. Action. Listener( handler ); Register minute. Field. add. Action. Listener( handler ); second. Field. add. Action. Listener( handler ); Action. Event. Handler exit. Button. add. Action. Listener( handler ); with GUI components Outline } // end constructor // display time in display. Field public void display. Time() { display. Field. set. Text( "The time is: " + time ); } // launch application: create, size and display Time. Test. Window; // when main terminates, program continues execution because a // window is displayed by the statements in main public static void main( String args[] ) { Time. Test. Window window = new Time. Test. Window(); Time. Test. Window. java Lines 59 -62 Register Action. Event. Hand ler with GUI components. window. set. Size( 400, 140 ); window. set. Visible( true ); } // end main 2003 Prentice Hall, Inc. All rights reserved.
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 // inner class declaration for handling JText. Field and JButton events private class Action. Event. Handler implements Action. Listener { // method to handle action events public void action. Performed( Action. Event event ) Declare inner class that implements { // user pressed exit. Button Action. Listener interface When user presses JButton or Enter key, if ( event. get. Source() == exit. Button ) method action. Performed is invoked System. exit( 0 ); // terminate the application Outline Time. Test. Window. java Line 85 Declare inner class Must implement method action. Performed // user pressed Enter key in hour. Field else if ( event. get. Source() == hour. Field ) { of Action. Listener Line 88 Must implement time. set. Hour( Integer. parse. Int( event. get. Action. Command() ) ); method Determine action depending hour. Field. set. Text( "" ); action. Performed on where event originated } // user pressed Enter key in minute. Field else if ( event. get. Source() == minute. Field ) { time. set. Minute( Integer. parse. Int( event. get. Action. Command() ) ); minute. Field. set. Text( "" ); } Line 88 When user presses button or key, method action. Performed is invoked Lines 91 -113 Determine action depending on where event originated 2003 Prentice Hall, Inc. All rights reserved.
108 // user pressed Enter key in second. Field 109 else if ( event. get. Source() == second. Field ) { 110 time. set. Second( Integer. parse. Int( 111 event. get. Action. Command() ) ); 112 second. Field. set. Text( "" ); 113 } 114 115 display. Time(); // call outer class's method 116 117 } // end method action. Performed 118 119 } // end inner class Action. Event. Handler 120 121 } // end class Time. Test. Window Outline Time. Test. Window. java 2003 Prentice Hall, Inc. All rights reserved.
Outline Time. Test. Window. java 2003 Prentice Hall, Inc. All rights reserved.
73 10. 9 Nested Classes (cont. ) • Anonymous inner class – Declared inside a method of a class – Has no name 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // Fig. 10. 23: Time. Test. Window 2. java // Demonstrating the Time class set and get methods import java. awt. *; import java. awt. event. *; import javax. swing. *; Outline public class Time. Test. Window 2 extends JFrame { private Time time; private JLabel hour. Label, minute. Label, second. Label; private JText. Field hour. Field, minute. Field, second. Field, display. Field; // constructor public Time. Test. Window 2() { // call JFrame constructor to set title bar string super( "Anonymous Inner Class Demonstration" ); time = new Time(); create. GUI(); register. Event. Handlers(); // create Time object // set up GUI // set up event handling Time. Test. Window. java } // create GUI components and attach to content pane private void create. GUI() { Container container = get. Content. Pane(); container. set. Layout( new Flow. Layout() ); 2003 Prentice Hall, Inc. All rights reserved.
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 hour. Label = new JLabel( "Set Hour" ); hour. Field = new JText. Field( 10 ); container. add( hour. Label ); container. add( hour. Field ); Outline minute. Label = new JLabel( "Set minute" ); minute. Field = new JText. Field( 10 ); container. add( minute. Label ); container. add( minute. Field ); second. Label = new JLabel( "Set Second" ); second. Field = new JText. Field( 10 ); container. add( second. Label ); container. add( second. Field ); display. Field = new JText. Field( 30 ); display. Field. set. Editable( false ); container. add( display. Field ); Time. Test. Window. java } // end method create. GUI // register event handlers for hour. Field, minute. Field and second. Field private void register. Event. Handlers() { 2003 Prentice Hall, Inc. All rights reserved.
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 // register hour. Field event handler hour. Field. add. Action. Listener( new Action. Listener() { // Define anonymous inner class that anonymous inner class implements Action. Listener public void action. Performed( Action. Event event ) { time. set. Hour( Integer. parse. Int( event. get. Action. Command() ) ); hour. Field. set. Text( "" ); display. Time(); Inner } } // end anonymous inner class ); // end call to add. Action. Listener for // register minute. Field event handler minute. Field. add. Action. Listener( Outline Time. Test. Window. java Line 54 Pass Actionclass implements method Listener to GUI action. Performedcomponent’s of method Action. Listeneradd. Action. Listener hour. Field Pass Action. Listener as argument to GUI component’s Line 56 method add. Action. Listener Define anonymous inner class new Action. Listener() { // anonymous inner class public void action. Performed( Action. Event event ) { Repeat process for JText. Field time. set. Minute( Integer. parse. Int( minute. Field event. get. Action. Command() ) ); minute. Field. set. Text( "" ); display. Time(); } Lines 58 -64 Inner class implements method action. Performed Lines 71 -85 Repeat process for minute. Field 2003 Prentice Hall, Inc. All rights reserved.
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 Outline } // end anonymous inner class ); // end call to add. Action. Listener for minute. Field second. Field. add. Action. Listener( new Action. Listener() { // anonymous Repeat process for JText. Field second. Field inner class public void action. Performed( Action. Event event ) { time. set. Second( Integer. parse. Int( event. get. Action. Command() ) ); second. Field. set. Text( "" ); display. Time(); } } // end anonymous inner class Time. Test. Window. java Line 87 -101 Repeat process for JText. Field second. Field ); // end call to add. Action. Listener for second. Field } // end method register. Event. Handlers // display time in display. Field public void display. Time() { display. Field. set. Text( "The time is: " + time ); } 2003 Prentice Hall, Inc. All rights reserved.
110 111 // create Time. Test. Window 2 object, register for its window events 112 // and display it to begin application's execution 113 public static void main( String args[] ) 114 { 115 Time. Test. Window 2 window = new Time. Test. Window 2(); 116 117 // register listener for window. Closing event 118 window. add. Window. Listener( Declare anonymous inner class 119 that extends Windows. Adapter 120 // anonymous inner class for window. Closing event Time. Test. Window. to enable closing of JFrame 121 new Window. Adapter() { java 122 123 // terminate application when user closes window 124 public void window. Closing( Window. Event event ) Line 121 -129 125 { Declare anonymous 126 System. exit( 0 ); inner class that 127 } extends 128 Windows. Adapter 129 } // end anonymous inner class to enable closing of 130 JFrame 131 ); // end call to add. Window. Listener for window 132 133 window. set. Size( 400, 105 ); 134 window. set. Visible( true ); 135 136 } // end main 137 138 } // end class Time. Test. Window 2 2003 Prentice Hall, Inc. All rights reserved. Outline
Outline Time. Test. Window. java 2003 Prentice Hall, Inc. All rights reserved.
80 10. 9 Nested Classes (Cont. ) • Notes on nested classes – Compiling class that contains nested class • Results in separate. class file – Inner classes with names can be declared as • public, protected, private or package access – Access outer class’s this reference Outer. Class. Name. this – Outer class is responsible for creating inner class objects – Nested classes can be declared static 2003 Prentice Hall, Inc. All rights reserved.
10. 10 Type-Wrapper Classes for Primitive Types • Type-wrapper class – Each primitive type has one • Character, Byte, Integer, Boolean, etc. – Enable to represent primitive as Object • Primitive types can be processed polymorphically – Declared as final – Many methods are declared static 2003 Prentice Hall, Inc. All rights reserved. 81
- Slides: 81