ObjectOriented Programming Outline Introduction Superclasses and Subclasses protected
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
Object-Oriented Programming Outline final Methods and Classes Abstract Superclasses and Concrete Classes Polymorphism Examples Case Study: A Payroll System Using Polymorphism New Classes and Dynamic Binding Case Study: Inheriting Interface and Implementation Case Study: Creating and Using Interfaces Inner Class Definitions Notes on Inner Class Definitions Type-Wrapper Classes for Primitive Types
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 viceversa – Form tree-like hierarchal structures • Create a hierarchy for class Shape (next slide)
Superclasses and Subclasses Shape Two. Dimensional. Shape Circle Square Triangle Three. Dimensional. Shape Sphere Cube Tetrahedron • Using inheritance – Use keyword extends class Two. Dimensional. Shape 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. method. Name
Modifiers The following table shows the access to members permitted by each modifier: Access Levels Modifier Class Package Subclass World public Y Y protected Y Y Y N no modifier Y Y N N private Y N N N
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. method. Name – 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
Relationship between Superclass Objects and Subclass Objects • Upcoming example 4 public class Point { – Every class implicitly inheirts from class Object 8 public Point() – Every constructor must call superclass constructor • Called implicitly by default • If explicit, must be first command 41 public class Circle extends Point { // inherits from Point – Inherits from Point 54 super( a, b ); // call to superclass constructor – Explicitly calls superclass (Point) constructor • Must be first statement in Circle constructor • To call default superclass construcor, use super()
Relationship between Superclass Objects and Subclass Objects – Both Point and Circle override to. String • To call class Point's to. String in class Circle • super. to. String() 83 Point point. Ref, p; 84 Circle circle. Ref, c; 88 c = new Circle( 2. 7, 120, 89 ); 95 point. Ref = c; // assign Circle to point. Ref – point. Ref points to a Circle object • Allowed, because Circle "is a" Point 98 point. Ref. to. String(); – point. Ref knows it is pointing to a Circle object • Calls the proper to. String method • Example of polymorphism - more later
Relationship between Superclass Objects and Subclass Objects 102 circle. Ref = (Circle) point. Ref; – point. Ref is pointing to a Circle • Downcast it to a Circle reference, assign to circle. Ref (explicit cast) 87 p = new Point( 30, 50 ); 113 if ( p instanceof Circle ) { – Operator instanceof • Returns true if object to which p points "is a" Circle • In this case, returns false
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 // Fig. 9. 4: Point. java // Definition of class Point public class Point { protected int x, y; // coordinates of the Point 1. Point definition 1. 1 Data members Point implicitly inherits from class // No-argument constructor Object public Point() { 1. 2 Constructors // implicit call to superclass constructor occurs here set. Point( 0, 0 ); Notice the default (no argument) 1. 3 Methods } constructor. Implicit call to superclass constructor. // Constructor public Point( int a, int b ) { // implicit call to superclass constructor occurs here set. Point( a, b ); } // Set x and y coordinates of Point public void set. Point( int a, int b ) { x = a; y = b; } // get x coordinate public int get. X() { return x; }
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 59 60 // get y coordinate public int get. Y() { return y; } // convert the point into a String representation public String to. String() Class { return "[" + x + ", " + y + "]"; } } // Fig. 9. 4: Circle. java // Definition of class Circle 1. 4 Overridden Point's methodto. String method to. String overrides --------the original to. String in class Object 1. Circle Definition public class Circle extends Point { // inherits from Point protected double radius; // No-argument constructor Point constructor called public Circle() { // implicit call to superclass constructor occurs here set. Radius( 0 ); } 1. 1 extends Point 1. 2 Multiple implicitly constructors // Constructor Point constructor called explicitly, public Circle( double r, int a, int b ) and must be the first statement in the { subclass constructor super( a, b ); // call to superclass constructor set. Radius( r ); } // Set radius of Circle public void set. Radius( double r ) { radius = ( r >= 0. 0 ? r : 0. 0 ); }
61 62 // Get radius of Circle 63 public double get. Radius() { return radius; } 64 65 // Calculate area of Circle 66 public double area() { return Math. PI * radius; } 67 68 // convert the Circle to a String 69 public String to. String() 70 { 71 return "Center = " + "[" + x + ", " + y + "]" + 72 "; Radius = " + radius; 73 } 74 } 1. 3 Overridden to. String method
75 // Fig. 9. 4: Test. java 76 // Demonstrating the "is a" relationship 77 import java. text. Decimal. Format; 78 import javax. swing. JOption. Pane; 1. Initialize objects 79 80 public class Inheritance. Test { 81 public static void main( String args[] ) 2. Refer to a subclass object with a superclass reference 82 { 83 Point point. Ref, p; 84 Circle circle. Ref, c; 85 String output; 2. 1 to. String 86 87 p = new Point( 30, 50 ); 88 c = new Circle( 2. 7, 120, 89 ); 89 Allowed because 90 output = "Point p: " + p. to. String() + a subclass object "is a" superclass object 91 "n. Circle c: " + c. to. String(); 92 The computer knows that 93 // use the "is a" relationship to refer to a Circle 94 95 point. Ref is actually pointing to a Circle object, so it calls method to. String of class // with a Point reference Circle. This is an example of polymorphism, more later. point. Ref = c; // assign Circle to point. Ref 96 97 output += "nn. Circle c (via point. Ref): " + 98 point. Ref. to. String();
99 100 // Use downcasting (casting a superclass reference to a 101 // subclass data type) to assign point. Ref to circle. Ref 102 circle. Ref = (Circle) point. Ref; 103 2. 2 Downcast 104 output += "nn. Circle c (via circle. Ref): " + Downcast point. Ref (which is 105 circle. Ref. to. String(); really pointing to a Circle) to 2. 3 to. String 106 a Circle, and assign it to 107 Decimal. Format precision 2 = new Decimal. Format( "0. 00" ); circle. Ref 108 output += "n. Area of c (via circle. Ref): " + 2. 4 area 109 precision 2. format( circle. Ref. area() ); 110 3. if statement 111 // Attempt to refer to Point object 112 // with Circle reference 113 if ( p instanceof Circle ) { 114 circle. Ref = (Circle) p; // line 40 in Test. java 115 output += "nncast successful"; 116 } 117 else 118 output += "nnp does not refer to a Circle"; 119 120 JOption. Pane. show. Message. Dialog( null, output, 121 "Demonstrating the "is a" relationship", 122 JOption. Pane. INFORMATION_MESSAGE ); 123 124 System. exit( 0 ); 125 } 126 } Test if p (class Point) "is a" Circle. It is not.
Program Output
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 method finalize defined – Subclass finalize should call superclass finalize as last action – Should be protected • Only subclasses have access 23 protected void finalize()
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. 5: Point. java // Definition of class Point public class Point extends Object { protected int x, y; // coordinates of the Point // no-argument constructor public Point() { x = 0; y = 0; System. out. println( "Point constructor: " + this ); } // constructor public Point( int a, int b ) { x = a; y = b; Only subclass may access System. out. println( "Point constructor: " + this ); } protected methods. // finalizer protected void finalize() { System. out. println( "Point finalizer: " + this ); } // convert the point into a String representation public String to. String() { return "[" + x + ", " + y + "]"; } } 1. Class Point 1. 1 Constructors 1. 2 Finalizer (protected)
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 // Fig. 9. 5: Circle. java // Definition of class Circle public class Circle extends Point { // inherits from Point protected double radius; // no-argument constructor public Circle() { // implicit call to superclass constructor here radius = 0; System. out. println( "Circle constructor: " + this ); } // Constructor public Circle( double r, int a, int b ) { super( a, b ); // call the superclass constructor radius = r; System. out. println( "Circle constructor: " + this ); 51 } 52 54 protected void finalize() 55 { 56 System. out. println( "Circle finalizer: " + this ); 57 super. finalize(); // call superclass finalize method 59 1. 1 Constructors 1. 2 Finalizer Circle finalizer calls superclass finalizer (in Point). 53 // finalizer 58 } 1. Class Circle (extends Point)
60 // convert the Circle to a String 61 public String to. String() 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 { return "Center = " + super. to. String() + "; Radius = " + radius; } } // Fig. 9. 5: Test. java // Demonstrate when superclass and subclass // constructors and finalizers are called. public class Test { public static void main( String args[] ) { Circle circle 1, circle 2; Mark objects for garbage collection by setting them to null. circle 1 = new Circle( 4. 5, 72, 29 ); circle 2 = new Circle( 10, 5, 5 ); circle 1 = null; // mark for garbage collection circle 2 = null; // mark for garbage collection System. gc(); // call the garbage collector } } Call garbage collector (static method gc of class System). 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” Birth. Date; //Wrong! Employee “has a” Birthdate; //Composition
Case Study: Point, Circle, Cylinder • Inheritance example – Class Point • protected variables x, y • Methods: set. Point, get. X, get. Y, to. String – Class Circle (extends Point) • protected variable radius • Methods: set. Radius, get. Radius, area, override to. String – Class Cylinder (extends Circle) • protected variable height • Methods: set. Height, get. Height, area (surface area), volume, override to. String
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. 6: Point. java // Definition of class Point package com. deitel. jhtp 3. ch 09; public class Point { protected int x, y; // coordinates of the Point // no-argument constructor public Point() { set. Point( 0, 0 ); } // constructor public Point( int a, int b ) { set. Point( a, b ); } // Set x and y coordinates of Point public void set. Point( int a, int b ) { x = a; y = b; } // get x coordinate public int get. X() { return x; } // get y coordinate public int get. Y() { return y; } // convert the point into a String representation public String to. String() { return "[" + x + ", " + y + "]"; } } 1. Class Point 1. 1 Instance variables 2. Constructors 2. 1 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. 7: Circle. java // Definition of class Circle package com. deitel. jhtp 3. ch 09; public class Circle extends Point { // inherits from Point protected double radius; // no-argument constructor public Circle() { // implicit call to superclass constructor set. Radius( 0 ); } // Constructor public Circle( double r, int a, int b ) { super( a, b ); // call the superclass constructor set. Radius( r ); } // Set radius of Circle public void set. Radius( double r ) { radius = ( r >= 0. 0 ? r : 0. 0 ); } // Get radius of Circle public double get. Radius() { return radius; } // Calculate area of Circle public double area() { return Math. PI * radius; } 1. Class Circle (extends Point) 1. 1 Instance variable 2. Constructors 2. 1 Methods
32 33 34 35 36 37 38 39 // convert the Circle to a String public String to. String() { return "Center = " + super. to. String() + "; Radius = " + radius; } } 2. 1 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 // Fig. 9. 8: Cylinder. java // Definition of class Cylinder package com. deitel. jhtp 3. ch 09; public class Cylinder extends Circle { protected double height; // height of Cylinder // No-argument constructor public Cylinder() { // implicit call to superclass constructor here set. Height( 0 ); } 1. Class Cylinder (extends Circle) 1. 1 Instance variable 2. Constructors 2. 1 Methods // constructor public Cylinder( double h, double r, int a, int b ) { super( r, a, b ); set. Height( h ); } // Set height of Cylinder public void set. Height( double h ) { height = ( h >= 0 ? h : 0 ); } // Get height of Cylinder public double get. Height() { return height; }
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 // 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 to. String() { return super. to. String() + "; Height = " + height; } } // Fig. 9. 8: Test. java 46 // Application to test class Cylinder 47 import javax. swing. JOption. Pane; 48 import java. text. Decimal. Format; 49 import com. deitel. jhtp 3. ch 09. Cylinder; 50 51 public class Test { 52 public static void main( String args[] ) 53 { 54 Cylinder c = new Cylinder( 5. 7, 2. 5, 12, 23 ); 55 Decimal. Format precision 2 = new Decimal. Format( "0. 00" ); 56 String output; 57 2. 1 Methods ------1. Class Test 2. main 2. 1 Initialize object
58 output = "X coordinate is " + c. get. X() + 59 "n. Y coordinate is " + c. get. Y() + 60 "n. Radius is " + c. get. Radius() + 61 "n. Height is " + c. get. Height(); 62 2. 2 Method calls 63 c. set. Height( 10 ); 64 c. set. Radius( 4. 25 ); 2. 3 Set methods 65 c. set. Point( 2, 2 ); 66 2. 4 Display changes 67 output += 68 "nn. The new location, radius " + 69 "and height of c aren" + c + 70 "n. Area is " + precision 2. format( c. area() ) + 71 "n. Volume is " + precision 2. format( c. volume() ); 72 73 JOption. Pane. show. Message. Dialog( null, output, 74 "Demonstrating Class Cylinder", 75 JOption. Pane. INFORMATION_MESSAGE ); 76 System. exit( 0 ); 77 } 78 } 2. 5 area and volume
Program Output
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 • Two. Dimensional. Shape - too generic to be concrete
Polymorphism Examples • Class Quadrilateral – Rectangle "is a" Quadrilateral – get. Perimeter 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 get. Perimeter using the references • Appropriate method called for each class • Adding a new subclass – Simply need to define get. Perimeter 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, Commission. Worker, and Piece. Worker, Hourly. Worker • Override methods to. String and earnings – Class Test • Initialize objects • Use an Employee reference and call to. String and earnings • Through polymorphism, the appropriate class method is called
1 2 // Fig. 9. 9: Employee. java // Abstract base class Employee 3 4 public abstract class Employee { 5 private String first. Name; 6 private String last. Name; 7 8 9 10 11 12 13 1. Class Employee (abstract base class) Class Employee declared // Constructor abstract, so no Employee public Employee( String first, String last ) objects can be created. { first. Name = first; last. Name = last; } 1. 1 Instance variables Employee can still have a 1. 2 Methods constructor, used by its derived classes. 1. 3 earnings (abstract method) 14 15 // Return the first name 16 public String get. First. Name() { return first. Name; } 17 18 // Return the last name 19 public String get. Last. Name() { return last. Name; } 20 21 public String to. String() 22 { return first. Name + ' ' + last. Name; } 23 abstract methods must be defined in concrete subclasses. 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 }
29 // Fig. 9. 9: Boss. java 30 // Boss class derived from Employee 31 32 public final class Boss extends Employee { 33 private double weekly. Salary; 34 1. Class Boss (extends Employee) 35 // Constructor for class Boss 36 public Boss( String first, String last, double s) 1. 1 Instance variable 37 { 38 super( first, last ); // call superclass constructor 39 set. Weekly. Salary( s ); 40 } 41 42 43 1. 2 Define earnings (required) Implementing earnings is required because 1. 3 Override to. String // Set the Boss's salary it was declared abstract and Boss is a public void set. Weekly. Salary( double s ) concrete class. 44 { weekly. Salary = ( s > 0 ? s : 0 ); } 45 46 // Get the Boss's pay 47 public double earnings() { return weekly. Salary; } 48 49 // Print the Boss's name 50 public String to. String() 51 { 52 return "Boss: " + super. to. String(); 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 82 83 84 // Fig. 9. 9: Commission. Worker. java // Commission. Worker class derived from Employee public final class Commission. Worker extends Employee { private double salary; // base salary per week private double commission; // amount per item sold private int quantity; // total items sold for week // Constructor for class Commission. Worker public Commission. Worker( String first, String last, double s, double c, int q) { super( first, last ); // call superclass constructor set. Salary( s ); set. Commission( c ); set. Quantity( q ); } // Set Commission. Worker's weekly base salary public void set. Salary( double s ) { salary = ( s > 0 ? s : 0 ); } // Set Commission. Worker's commission public void set. Commission( double c ) { commission = ( c > 0 ? c : 0 ); } // Set Commission. Worker's quantity sold public void set. Quantity( int q ) { quantity = ( q > 0 ? q : 0 ); } 1. Class Commission. Worker (extends Employee) 1. 1 Instance variables 1. 2 Constructor
85 // Determine Commission. Worker's earnings 86 public double earnings() 87 { return salary + commission * quantity; } 88 89 // Print the Commission. Worker's name 90 public String to. String() 91 { 92 return "Commission worker: " + super. to. String(); 93 } 94 } 95 // Fig. 9. 9: Piece. Worker. java 96 // Piece. Worker class derived from Employee 97 98 public final class Piece. Worker extends Employee { 99 private double wage. Per. Piece; // wage per piece output 100 private int quantity; // output for week 101 102 // Constructor for class Piece. Worker 103 public Piece. Worker( String first, String last, 104 double w, int q ) 105 { 106 super( first, last ); // call superclass constructor 107 set. Wage( w ); 108 set. Quantity( q ); 109 } 110 111 // Set the wage 112 public void set. Wage( double w ) 113 { wage. Per. Piece = ( w > 0 ? w : 0 ); } 114 1. 3 Define earnings (required) 1. 4 Override to. String --------1. Class Piece. Worker (extends Employee) 1. 1 Constructor
115 // Set the number of items output 116 public void set. Quantity( int q ) 117 { quantity = ( q > 0 ? q : 0 ); } 118 119 // Determine the Piece. Worker's earnings 120 public double earnings() 121 { return quantity * wage. Per. Piece; } 122 123 public String to. String() 124 { 125 return "Piece worker: " + super. to. String(); 126 } 127 } 128 // Fig. 9. 9: Hourly. Worker. java 129 // Definition of class Hourly. Worker 130 131 public final class Hourly. Worker extends Employee { 132 private double wage; // wage per hour 133 private double hours; // hours worked for week 134 135 // Constructor for class Hourly. Worker 136 public Hourly. Worker( String first, String last, 137 double w, double h ) 138 { 139 super( first, last ); // call superclass constructor 140 set. Wage( w ); 141 set. Hours( h ); 142 } 143 1. 2 Define earnings (required) 1. 3 Override to. String --------1. Class Hourly. Worker (extends Employee) 1. 1 Constructor
144 // Set the wage 145 public void set. Wage( double w ) 146 { wage = ( w > 0 ? w : 0 ); } 147 1. 2 Define earnings (required) 148 // Set the hours worked 149 public void set. Hours( double h ) 150 { hours = ( h >= 0 && h < 168 ? h : 0 ); } 151 1. 3 Override to. String 152 // Get the Hourly. Worker's pay 153 public double earnings() { return wage * hours; } 154 ------------ 155 public String to. String() 156 { 157 return "Hourly worker: " + super. to. String(); 158 } 159 } 160 // Fig. 9. 9: Test. java 161 // Driver for Employee hierarchy 162 import javax. swing. JOption. Pane; References to abstract classes are allowed. 163 import java. text. Decimal. Format; 164 165 public class Test { 166 public static void main( String args[] ) 167 { 168 Employee ref; // superclass reference 169 String output = ""; 170 1. Class Test 1. 1 Employee reference
171 Boss b = new Boss( "John", "Smith", 800. 00 ); 172 Commission. Worker c = 173 new Commission. Worker( "Sue", "Jones", 174 400. 0, 3. 0, 150); 1. 2 Through Initialize subclass 175 Piece. Worker p = Employee reference ref points to Boss object. 176 new Piece. Worker( "Bob", "Lewis", 2. 5, 200 ); polymorphism, the appropriate Boss versionsobjects of 177 Hourly. Worker h = to. String and earnings are called. To check, they are 178 new Hourly. Worker( "Karen", "Price", 13. 75, 40 ); called through the Boss object as well. 2. Method calls 179 through Employee 180 Decimal. Format precision 2 = new Decimal. Format( "0. 00" ); reference 181 182 ref = b; // Employee reference to a Boss 183 output += ref. to. String() + " earned $" + 184 precision 2. format( ref. earnings() ) + "n" + 185 b. to. String() + " earned $" + 186 precision 2. format( b. earnings() ) + "n"; 187 188 ref = c; // Employee reference to a Commission. Worker 189 output += ref. to. String() + " earned $" + 190 precision 2. format( ref. earnings() ) + "n" + 191 c. to. String() + " earned $" + 192 precision 2. format( c. earnings() ) + "n"; 193 194 ref = p; // Employee reference to a Piece. Worker 195 output += ref. to. String() + " earned $" + 196 precision 2. format( ref. earnings() ) + "n" + 197 p. to. String() + " earned $" + 198 precision 2. format( p. earnings() ) + "n"; 199
200 ref = h; // Employee reference to an Hourly. Worker 201 output += ref. to. String() + " earned $" + 202 precision 2. format( ref. earnings() ) + "n" + 203 h. to. String() + " earned $" + 204 precision 2. format( h. earnings() ) + "n"; 205 206 JOption. Pane. show. Message. Dialog( null, output, 207 "Demonstrating Polymorphism", 2. Method calls through Employee reference 208 JOption. Pane. INFORMATION_MESSAGE ); 209 System. exit( 0 ); 210 } 211 } Program Output
New Classes and Dynamic Binding • Dynamic binding (late binding) – Accomodates new classes – Object's type does not need to be known at compile time – At execution time, method call matched with object
Case Study: Inheriting Interface and Implementation • Polymorphism example – abstract superclass Shape • Subclasses Point, Circle, Cylinder • abstract method – get. Name • non-abstract methods – area (return 0. 0) – volume (return 0. 0) – Class Shape used to define a set of common methods • Interface is the three common methods • Implementation of area and volume used for first levels of heirarchy
Case Study: Inheriting Interface and Implementation – Create an array of Shape references • Point to various subclass objects • Call methods using Shape reference 159 array. Of. Shapes[ i ]. get. Name() + ": " + 160 array. Of. Shapes[ i ]. to. String() +
1 // Fig. 9. 10: Shape. java 2 // Definition of abstract base class Shape 3 4 public abstract class Shape extends Object { 5 public double area() { return 0. 0; } 6 public double volume() { return 0. 0; } 7 public abstract String get. Name(); 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. 10: Point. java // Definition of class Point Methds area and volume are defined. They will be overridden in the subclasses public class Point extends Shape { when necessary. protected int x, y; // coordinates of the Point // no-argument constructor public Point() { set. Point( 0, 0 ); } // constructor public Point( int a, int b ) { set. Point( a, b ); } // Set x and y coordinates of Point public void set. Point( int a, int b ) { x = a; y = b; } // get x coordinate public int get. X() { return x; } 1. Class Shape (abstract superclass) 1. 1 get. Name (abstract method) -----------1. Class Point (extends Shape) 1. 1 protected data members 1. 2 Constructors 1. 3 New methods
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 // get y coordinate public int get. Y() { return y; } // convert the point into a String representation public String to. String() abstract { return "[" + x + ", " + y + "]"; } 1. 4 Overridden method get. Name must be get. Name (required) overridden in a concrete subclass. ----------- // return the class name public String get. Name() { return "Point"; } } // Fig. 9. 10: Circle. java // Definition of class Circle public class Circle extends Point { // inherits from Point protected double radius; // no-argument constructor public Circle() { // implicit call to superclass constructor here set. Radius( 0 ); } // Constructor public Circle( double r, int a, int b ) { super( a, b ); // call the superclass constructor set. Radius( r ); } 1. Class Circle (extends Point) 1. 1 protected data member 1. 2 Constructors 1. 3 New methods
61 62 63 64 65 // Set radius of Circle public void set. Radius( double r ) { radius = ( r >= 0 ? r : 0 ); } // Get radius of Circle 66 public double get. Radius() { return radius; } 67 68 // Calculate area of Circle 69 public double area() { return Math. PI * radius; } 70 1. 4 Overridden method area 1. 5 Overridden method to. String 71 // convert the Circle to a String Circle overrides method area, { return "Center = " + super. to. String() + inherited from Shape. Point did 1. 6 not Overridden method get. Name (required) "; Radius = " + radius; } override area, and has the default ----------implementation (returns 0). 72 public String to. String() 73 74 75 76 // return the class name 77 public String get. Name() { return "Circle"; } 78 } 79 80 81 82 83 84 85 86 87 88 89 90 // Fig. 9. 10: Cylinder. java // Definition of class Cylinder public class Cylinder extends Circle { protected double height; // height of Cylinder // no-argument constructor public Cylinder() { // implicit call to superclass constructor here set. Height( 0 ); } Class Cylinder (extends Circle) 1. 1 protected data member 1. 2 Constructors
91 92 // constructor 93 public Cylinder( double h, double r, int a, int b ) 94 { 95 super( r, a, b ); // call superclass constructor 96 set. Height( h ); 97 } 98 99 // Set height of Cylinder 100 public void set. Height( double h ) 101 { height = ( h >= 0 ? h : 0 ); } 102 103 // Get height of Cylinder 104 public double get. Height() { return height; } 105 106 // Calculate area of Cylinder (i. e. , surface area) 107 public double area() 108 { 109 return 2 * super. area() + 110 2 * Math. PI * radius * height; 111 } 112 113 // Calculate volume of Cylinder 114 public double volume() { return super. area() * height; } 115 116 // Convert a Cylinder to a String 117 public String to. String() 118 { return super. to. String() + "; Height = " + height; } 119 120 // Return the class name 121 public String get. Name() { return "Cylinder"; } 122 } 1. 2 Constructors 1. 3 New methods 1. 4 Overridden method area 1. 5 Overridden method to. String 1. 6 Overridden method get. Name
123 // Fig. 9. 10: Test. java 124 // Driver for point, circle, cylinder hierarchy 125 import javax. swing. JOption. Pane; Class Test (driver) 126 import java. text. Decimal. Format; 127 128 public class Test { 1. import 129 public static void main( String args[] ) 130 { 131 Point point = new Point( 7, 11 ); 1. 1 Initialize objects Create an array of Shape 132 Circle circle = new Circle( 3. 5, 22, 8 ); references. 133 Cylinder cylinder = new Cylinder( 10, 3. 3, 10 ); 1. 2 Create array of 134 Shape references 135 Shape array. Of. Shapes[]; Point the Shape references 136 towards subclass objects. 137 array. Of. Shapes = new Shape[ 3 ]; 1. 3 Initialize array 138 139 // aim array. Of. Shapes[0] at subclass Point object 140 array. Of. Shapes[ 0 ] = point; 2. Call methods using 141 subclass references 142 // aim array. Of. Shapes[1] at subclass Circle object 143 array. Of. Shapes[ 1 ] = circle; 144 145 // aim array. Of. Shapes[2] at subclass Cylinder object 146 array. Of. Shapes[ 2 ] = cylinder; 147 148 String output = 149 point. get. Name() + ": " + point. to. String() + "n" + 150 circle. get. Name() + ": " + circle. to. String() + "n" + 151 cylinder. get. Name() + ": " + cylinder. to. String();
152 153 Decimal. Format precision 2 = new Decimal. Format( "0. 00" ); 154 155 // Loop through array. Of. Shapes and print the name, 156 // area, and volume of each object. 2. 1 Call methods using Shape references 157 for ( int i = 0; i < array. Of. Shapes. length; i++ ) { 158 output += "nn" + 159 array. Of. Shapes[ i ]. get. Name() + ": " + 160 array. Of. Shapes[ i ]. to. String() + 161 "n. Area = " + Call methods using superclass 162 precision 2. format( array. Of. Shapes[ i ]. area() ) + references. Appropriate method called because of polymorphism. 164 precision 2. format( array. Of. Shapes[ i ]. volume() ); 163 "n. Volume = " + 165 } 166 167 JOption. Pane. show. Message. Dialog( null, output, 168 "Demonstrating Polymorphism", 169 JOption. Pane. INFORMATION_MESSAGE ); 170 171 System. exit( 0 ); 172 } 173 }
Program Output
Case Study: Creating and Using Interfaces • Interface – Keyword interface – Has set of public abstract methods – Can contain public final static data • Using interfaces – Class specifies it uses interface with keyword implements • Multiple interfaces use comma-separated list – Class must define all abstract methods in interface • Must use same number of arguments, same return type – Using interface like signing a contract • "I will define all methods specified in the interface" – Same "is a" relationship as inheritance
Case Study: Creating and Using Interfaces • Using interfaces (continued) – Interfaces used in place of abstract classes • Used when no default implementation – Typically public data types • Interface defined in its own. java file • Interface name same as file name – Previous interfaces • We have used interface Action. Listener • Required to define action. Performed
Case Study: Creating and Using Interfaces • Another use of interfaces – Define a set of constants used by many classes public interface Constants { public static final int ONE = 1; public static final int TWO = 2; public static final int THREE = 3; } • Reexamine previous heirarchy – Replace abstract class Shape with interface Shape
1 // Fig. 9. 11: Shape. java 2 // Definition of interface Shape 3 Interface Shape is in its own file, Shape. java 4 public interface Shape { 5 public abstract double area(); 6 public abstract double volume(); 7 public abstract String get. Name(); 1. 1 abstract methods 8 } ------------ 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // Fig. 9. 11: 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() { set. Point( 0, 0 ); } 1. Shape interface 1. Class Point (implements Shape) Because Point implements interface Shape, it is required to define the // constructor public Point( int a, int b ) { set. Point( a, b ); } abstract methods in Shape. // Set x and y coordinates of Point public void set. Point( int a, int b ) { x = a; y = b; }
28 29 30 31 32 33 34 // get x coordinate public int get. X() { return x; } // get y coordinate public int get. Y() { return y; } // convert the point into a String representation 1. 1 Define method area (required) Point required to define the abstract 35 public String to. String() 1. 2 Define 36 { return "[" + x + ", " + y + "]"; } methods of the interface it implements. 37 38 // return the area 39 public double area() { return 0. 0; } 40 41 // return the volume method volume (required) 1. 3 Define method get. Name (required) 42 public double volume() { return 0. 0; } 43 44 // return the class name 45 public String get. Name() { return "Point"; } 46 } ----------Class Circle and Cylinder defined as before
123 // Fig. 9. 11: Test. java 124 // Driver for point, circle, cylinder hierarchy 125 import javax. swing. JOption. Pane; 126 import java. text. Decimal. Format; 127 128 public class Test { 129 public static void main( String args[] ) 130 { 131 Point point = new Point( 7, 11 ); 132 Circle circle = new Circle( 3. 5, 22, 8 ); 133 Cylinder cylinder = new Cylinder( 10, 3. 3, 10 ); 134 135 Shape array. Of. Shapes[]; 136 137 array. Of. Shapes = new Shape[ 3 ]; 138 139 // aim array. Of. Shapes[0] at subclass Point object 140 array. Of. Shapes[ 0 ] = point; 141 142 // aim array. Of. Shapes[1] at subclass Circle object 143 array. Of. Shapes[ 1 ] = circle; 144 145 // aim array. Of. Shapes[2] at subclass Cylinder object 146 array. Of. Shapes[ 2 ] = cylinder; 147 148 String output = 149 point. get. Name() + ": " + point. to. String() + "n" + 150 circle. get. Name() + ": " + circle. to. String() + "n" + 151 cylinder. get. Name() + ": " + cylinder. to. String(); Use same class Test as before
152 153 Decimal. Format precision 2 = new Decimal. Format( "0. 00" ); 154 155 // Loop through array. Of. Shapes and print the name, 156 // area, and volume of each object. 157 for ( int i = 0; i < array. Of. Shapes. length; i++ ) { 158 output += "nn" + 159 array. Of. Shapes[ i ]. get. Name() + ": " + 160 array. Of. Shapes[ i ]. to. String() + 161 "n. Area = " + 162 precision 2. format( array. Of. Shapes[ i ]. area() ) + 163 "n. Volume = " + 164 precision 2. format( array. Of. Shapes[ i ]. volume() ); 165 } 166 167 JOption. Pane. show. Message. Dialog( null, output, 168 "Demonstrating Polymorphism", 169 JOption. Pane. INFORMATION_MESSAGE ); 170 171 System. exit( 0 ); 172 } 173 } Use same class Test as before
Program Output
Inner Class Definitions • Inner classes – Till now, all classes defined at file scope (not inside other classes) – Inner classes defined inside other classes • Can access all members of outer class • No special handles needed – Anonymous inner class • Has no name – Frequently used with event handling
Inner Class Definitions • Windowed applications – Execute an application in its own window (like an applet) 64 public class Time. Test. Window extends JFrame { • Inherit from class JFrame (javax. swing) rather than JApplet • Call constructor to set title: super( "Title. Name" ) – init method replaced by constructor • init not guaranteed to be called (only called for Applets) • Instead, create GUI components in constructor • Instantiate object in main (guaranteed to be called) 117 Time. Test. Window window = new Time. Test. Window();
Inner Class Definitions • Window Title bar Minimize, maximize, and close
Inner Class Definitions 123 // INNER CLASS DEFINITION FOR EVENT HANDLING 124 private class Action. Event. Handler implements Action. Listener { – Event handling – Some class must implement interface Action. Listener • Must define method action. Performed • Class that implements Action. Listener "is an" Action. Listener 79 // create an instance of the inner class 80 Action. Event. Handler handler = new Action. Event. Handler(); 85 hour. Field. add. Action. Listener( handler ); – Method add. Action. Listener • Takes object of type Action. Listener • Pass it instance of the class that implements Action. Listener ("is a" relationship)
Inner Class Definitions • Example – We will use the Time class and execute an application in its own window – Use event handling to set the time • Define an inner class that implements Action. Listener • Use an object of this class as the event handler
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: Time. java // Time class definition import java. text. Decimal. Format; // used for number formatting // 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 1. Time class // Time constructor initializes each instance variable // to zero. Ensures that Time object starts in a // consistent state. public Time() { set. Time( 0, 0, 0 ); } 1. 3 Constructors // Set a new time value using universal time. Perform // validity checks on the 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 } // set the hour public void set. Hour( int h ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); } // set the minute public void set. Minute( int m ) { minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); } 1. 2 Data members 1. 4 Methods
32 33 // set the second 34 35 36 37 38 39 40 41 42 43 44 45 46 public void set. Second( int s ) { second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } // get the hour public int get. Hour() { return hour; } // get the minute public int get. Minute() { return minute; } // get the second public int get. Second() { return second; } // Convert to String in standard-time format 47 public String to. String() 48 { 49 Decimal. Format two. Digits = new Decimal. Format( "00" ); 50 51 return ( ( get. Hour() == 12 || get. Hour() == 0 ) ? 52 12 : get. Hour() % 12 ) + ": " + 53 two. Digits. format( get. Minute() ) + ": " + 54 two. Digits. format( get. Second() ) + 55 ( get. Hour() < 12 ? " AM" : " PM" ); 56 } 57 } 1. 4 Methods
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 83 84 85 86 87 88 // Fig. 9. 12: Time. Test. Window. java // Demonstrating the Time class set and get methods import java. awt. *; Set up all GUI components in import java. awt. event. *; constructor. In main, create a import javax. swing. *; 1. import Time. Test. Window object, which public class Time. Test. Window extends JFrame { runs the constructor. 1. 1 Class Time. Test. Window ( private Time t; extends JFrame) private JLabel hour. Label, minute. Label, second. Label; Call to JFrame constructor sets title bar of private JText. Field hour. Field, minute. Field, window. second. Field, display; 1. 2 Create GUI private JButton exit. Button; components in public Time. Test. Window() constructor { super( "Inner Class Demonstration" ); 1. 3 Create instance of t = new Time(); class that implements Action. Listener Object of inner class Action. Event. Handler Container c = get. Content. Pane(); passed as an argument to add. Action. Listener // create an instance of the inner class Action. Event. Handler handler = new Action. Event. Handler(); c. set. Layout( new Flow. Layout() ); hour. Label = new JLabel( "Set Hour" ); hour. Field = new JText. Field( 10 ); hour. Field. add. Action. Listener( handler ); c. add( hour. Label ); c. add( hour. Field ); 1. 4 add. Action. Listener
89 minute. Label = new JLabel( "Set minute" ); 90 minute. Field = new JText. Field( 10 ); 91 minute. Field. add. Action. Listener( handler ); 92 c. add( minute. Label ); 1. 5 Create GUI 93 c. add( minute. Field ); 94 components 95 second. Label = new JLabel( "Set Second" ); 96 second. Field = new JText. Field( 10 ); 2. Methods 97 second. Field. add. Action. Listener( handler ); 98 c. add( second. Label ); 99 c. add( second. Field ); 3. main 100 101 display = new JText. Field( 30 ); 3. 1 Create object 102 display. set. Editable( false ); 103 c. add( display ); 104 105 exit. Button = new JButton( "Exit" ); 106 exit. Button. add. Action. Listener( handler ); 107 c. add( exit. Button ); 108 } 109 110 public void display. Time() Create Time. Test. Window object. 111 { 112 display. set. Text( "The time is: " + t ); 113 } 114 115 public static void main( String args[] ) 116 { 117 Time. Test. Window window = new Time. Test. Window();
118 119 window. set. Size( 400, 140 ); 120 window. show(); 121 } 122 123 // INNER CLASS DEFINITION FOR EVENT HANDLING 4. Inner class 124 private class Action. Event. Handler implements Action. Listener { Action. Event. Handler 125 public void action. Performed( Action. Event e ) implements 126 { Action. Listener 127 if ( e. get. Source() == exit. Button ) 128 System. exit( 0 ); // terminate the application 129 else if ( e. get. Source() == hour. Field ) { 130 t. set. Hour( Use a named inner class as the event 131 Integer. parse. Int( e. get. Action. Command() ) ); 132 hour. Field. set. Text( "" ); handler. Class implements interface 133 } Action. Listener, and must define 134 else if ( e. get. Source() == minute. Field ) { action. Performed. 135 t. set. Minute( 136 Integer. parse. Int( e. get. Action. Command() ) ); 137 minute. Field. set. Text( "" ); 138 } 139 else if ( e. get. Source() == second. Field ) { 140 t. set. Second( 141 Integer. parse. Int( e. get. Action. Command() ) ); 142 second. Field. set. Text( "" ); 143 } 144 145 display. Time(); 146 } 147 } 148 }
Program Output
Inner Class Definitions • Anonymous inner classes – Have no name – Object created at time class defined • Event handling with anonymous inner classes – Define the inner class inside the call to add. Action. Listener • Create an instance of the class inside the method call • add. Action. Listener takes an object of class Action. Listener
Inner Class Definitions 24 hour. Field. add. Action. Listener( 25 new Action. Listener() { // anonymous inner class 26 public void action. Performed( Action. Event e ) 27 { 28 t. set. Hour( 29 Integer. parse. Int( e. get. Action. Command() ) ); 30 31 32 33 34 hour. Field. set. Text( "" ); display. Time(); } ); – new creates an object – Action. Listener() • Begins definition of anonymous class and calls default constructor • Similar to public class my. Handler implements Action. Listener – Braces ( {} ) begin and end class defintion
Inner Class Definitions 82 84 85 86 Time. Test. Window window = new Time. Test. Window(); window. add. Window. Listener( new Window. Adapter() { public void window. Closing( Window. Event e ) 87 { 88 System. exit( 0 ); 89 } 90 } 91 ); – Enables use of close box (window closing event) • add. Window. Listener registers window event listener • 7 methods need to be defined for interface Window. Listener • Adapter classes - already implement interfaces – Extend adapter class and override methods want to define • Adapter class "is a" Window. Listener
Inner Class Definitions 82 84 85 86 Time. Test. Window window = new Time. Test. Window(); window. add. Window. Listener( new Window. Adapter() { public void window. Closing( Window. Event e ) 87 { 88 System. exit( 0 ); 89 } 90 } 91 ); – new Window. Adapter() • Begins anonymous inner class that extends Window. Adapter • Similar to: public class my. Handler extends Window. Adapter {
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. 9. 13: Time. Test. Window. java // Demonstrating the Time class set and get methods import java. awt. *; import java. awt. event. *; import javax. swing. *; public class Time. Test. Window extends JFrame { private Time t; private JLabel hour. Label, minute. Label, second. Label; private JText. Field hour. Field, minute. Field, second. Field, display; public Time. Test. Window() { super( "Inner Class Demonstration" ); 1. import 1. 1 Class Time. Test. Window (extends JFrame) 1. 2 Constructor 1. 3 Initialze GUI t = new Time(); Container c = get. Content. Pane(); An object of an anonymous inner class handler ( 2. Event is used as the event handler. anonymous inner c. set. Layout( new Flow. Layout() ); hour. Label = new JLabel( "Set Hour" ); hour. Field = new JText. Field( 10 ); hour. Field. add. Action. Listener( 25 new Action. Listener() { // anonymous inner class 26 public void action. Performed( Action. Event e ) 27 { 28 t. set. Hour( 29 Integer. parse. Int( e. get. Action. Command() ) ); class)
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 hour. Field. set. Text( "" ); display. Time(); } ); c. add( hour. Label ); c. add( hour. Field ); 2. Event handler ( Each button has a separate inner class anonymous inner as an event handler. class) minute. Label = new JLabel( "Set minute" ); minute. Field = new JText. Field( 10 ); minute. Field. add. Action. Listener( new Action. Listener() { // anonymous inner class public void action. Performed( Action. Event e ) { t. set. Minute( Integer. parse. Int( e. get. Action. Command() ) ); minute. Field. set. Text( "" ); display. Time(); } ); c. add( minute. Label ); c. add( minute. Field ); second. Label = new JLabel( "Set Second" ); second. Field = new JText. Field( 10 ); second. Field. add. Action. Listener( new Action. Listener() { // anonymous inner class public void action. Performed( Action. Event e )
59 60 61 62 63 64 { t. set. Second( Integer. parse. Int( e. get. Action. Command() ) ); second. Field. set. Text( "" ); display. Time(); } 65 } 66 ); 67 c. add( second. Label ); 68 c. add( second. Field ); 3. main 3. 1 Create Time. Test. Window object 69 70 display = new JText. Field( 30 ); 71 display. set. Editable( false ); 3. 2 add. Window. Listener 72 c. add( display ); 73 } 74 75 76 77 78 79 80 81 82 83 84 85 public void display. Time() { display. set. Text( "The time is: " + t ); } Use an anonymous inner class public static void main( String args[] ) to handle window events. { Time. Test. Window window = new Time. Test. Window(); window. add. Window. Listener( new Window. Adapter() {
86 public void window. Closing( Window. Event e ) 87 { 88 System. exit( 0 ); 89 } 90 } 91 ); 92 93 window. set. Size( 400, 120 ); 94 window. show(); 95 } 96 } Program Output
Notes on Inner Class Definitions • Notes – Every class (including inner classes) have their own. class file – Named inner classes can be public, protected, private, or have package access • Same restrictions as other members of a class – To access outer class's this reference • Outer. Class. Name. this – Inner class can be static • Does not have access to outer class's non-static members
Notes on Inner Class Definitions • Notes (continued) – To create an object of another class's inner class • Create an object of outer class and assign it a reference (ref) • Type statement of form: Outer. Classname ref = new Outer. Classname(); Outer. Class. Name. Inner. Class. Name inner. Ref = ref. new Inner. Class. Name();
Type-Wrapper Classes for Primitive Types • Type wrapper classes – Each primitive data type has one • Called Character, Byte, Short, Integer, Long, Float, Double, Boolean – Manipulate primitive types like objects of class Object • Values can be processed polymorphically – Declared final, so methods implicitly final • Cannot be overridden – Numeric classes inherit from Number • Byte, Short, Integer, Long, Float, Double – Many methods are static – Check documentation if manipulating primitive types • Method you need may be defined
- Slides: 90