Java ObjectOriented Programming Outline 1 Introduction 2 Superclasses
Java Object-Oriented Programming Outline 1 Introduction 2 Superclasses and Subclasses 3 protected Members 4 Relationship between Superclass Objects and Subclass Objects 5 Implicit Subclass-Object-to-Superclass-Object Conversion 6 Software Engineering with Inheritance 7 Composition vs. Inheritance 8 Introduction to Polymorphism 9 Type Fields and switch Statements 10 Dynamic Method Binding 11 final Methods and Classes 12 Abstract Superclasses and Concrete Classes 13 Polymorphism Example 14 New Classes and Dynamic Binding 15 Case Study: Inheriting Interface and Implementation 16 Case Study: Creating and Using Interfaces 17 Inner Class Definitions 18 Notes on Inner Class Definitions 2000 Prentice Hall, Inc. All rights reserved. 1
1. Introduction • Object-Oriented Programming (OOP) – Inheritance - form of software reusability • New classes created from existing ones • Absorb attributes and behaviors, 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 hierarchy – Polymorphism • Write programs in a general fashion to handle a wide variety of classes – Abstraction - seeing the big picture 2000 Prentice Hall, Inc. All rights reserved. 2
1 Introduction (II) • 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 2000 Prentice Hall, Inc. All rights reserved. 3
2 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) 2000 Prentice Hall, Inc. All rights reserved. 4
2 Superclasses and Subclasses (II) 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 2000 Prentice Hall, Inc. All rights reserved. 5
3 protected Members • In a superclass – public members • Accessible anywhere program has a reference to a superclass or subclass type – private members • Accessible 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 2000 Prentice Hall, Inc. All rights reserved. 6
4 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 2000 Prentice Hall, Inc. All rights reserved. 7
4 Relationship between Superclass Objects and Subclass Objects (II) • Overriding methods – Subclass can redefine superclass method • When method mentioned in subclass, subclass version used • Access original superclass method with super. method. Name – To invoke superclass constructor explicitly (called implicitly by default) • super(); //can pass arguments if needed • If called explicitly, must be first statement • Every Applet has used these techniques – Inheritance concept formalized – Java implicitly uses class Object as superclass for all classes – We have overridden init and paint when we extended JApplet 2000 Prentice Hall, Inc. All rights reserved. 8
1// Fig. 27. 3: Point. java 2// Definition of class Point 3 4 public class Point { 5 protected int x, y; // coordinates of the Point 6 7 // No-argument constructor 8 public Point() 9 { 10 // implicit call to superclass constructor occurs here 11 set. Point( 0, 0 ); 12 } 13 14 // Constructor 15 public Point( int a, int b ) 16 { 17 // implicit call to superclass constructor occurs here 18 set. Point( a, b ); 19 } 20 21 // Set x and y coordinates of Point 22 public void set. Point( int a, int b ) 23 { 24 x = a; 25 y = b; 26 } 27 28 // get x coordinate 29 public int get. X() { return x; } 30 2000 Prentice Hall, Inc. All rights reserved. Outline 1. Point definition 1. 1 Data members 1. 2 Constructors 1. 3 Methods
31 32 33 34 35 36 37 38 // get y coordinate public int get. Y() { return y; } // convert the point into a String representation public String to. String() { return "[" + x + ", " + y + "]"; } } // Fig. 27. 3: Circle. java 39 // Definition of class Circle 40 41 public class Circle extends Point { // inherits from Point 42 protected double radius; 43 44 45 46 47 48 49 50 51 52 53 // No-argument constructor public Circle() { // implicit call to superclass constructor occurs here set. Radius( 0 ); } // Constructor public Circle( double r, int a, int b ) { 54 super( a, b ); // call to superclass constructor 55 set. Radius( r ); 56 } 57 58 // Set radius of Circle 59 public void set. Radius( double r ) 60 { radius = ( r >= 0. 0 ? r : 0. 0 ); } 2000 Prentice Hall, Inc. All rights reserved. Outline 1. 2 Methods --------1. Circle Definition 1. 1 extends Point 1. 2 Multiple constructors
61 62 // Get radius of Circle Outline 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 } 2000 Prentice Hall, Inc. All rights reserved. 1. 3 Overridden to. String method
75 // Fig. 27. 3: Inheritance. Test. java 76 // Demonstrating the "is a" relationship 77 import java. text. Decimal. Format; 78 import javax. swing. JOption. Pane; 79 80 public class Inheritance. Test { 81 public static void main( String args[] ) 82 { 83 Point point. Ref, p; 84 Circle circle. Ref, c; 85 String output; 86 87 p = new Point( 30, 50 ); 88 c = new Circle( 2. 7, 120, 89 ); 89 90 output = "Point p: " + p. to. String() + 91 "n. Circle c: " + c. to. String(); 92 93 // use the "is a" relationship to refer to a Circle 94 // with a Point reference 95 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 104 output += "nn. Circle c (via circle. Ref): " + 105 circle. Ref. to. String(); 2000 Prentice Hall, Inc. All rights reserved. Outline 1. Initialize objects 2. Refer to a subclass object with a superclass reference 2. 1 to. String 2. 2 Downcast 2. 3 to. String
106 107 Decimal. Format precision 2 = new Decimal. Format( "0. 00" ); Outline 108 output += "n. Area of c (via circle. Ref): " + 109 precision 2. format( circle. Ref. area() ); 110 2. 4 Print area 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 } 2000 Prentice Hall, Inc. All rights reserved. 3. if statement
Outline Program Output 2000 Prentice Hall, Inc. All rights reserved.
5 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 2000 Prentice Hall, Inc. All rights reserved. 15
6 Software Engineering with Inheritance • Inheritance – Customize existing software • Create a new class, add attributes and behaviors as needed • Software reuse key to large-scale projects – Java and OOP does this – Availability of class libraries and inheritance • Superclass – Specifies commonality – Look for commonality among a set of classes • "Factor it out" to form the superclass – Subclasses are then customized 2000 Prentice Hall, Inc. All rights reserved. 16
7 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 2000 Prentice Hall, Inc. All rights reserved. 17
8 Introduction to Polymorphism • With polymorphism – Write extensible programs – Generically process superclass objects – Easy to add classes to hierarchy • Little or no modification required • Only parts of program that need direct knowledge of new class must be changed 2000 Prentice Hall, Inc. All rights reserved. 18
9 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 2000 Prentice Hall, Inc. All rights reserved. 19
10 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 2000 Prentice Hall, Inc. All rights reserved. 20
11 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 2000 Prentice Hall, Inc. All rights reserved. 21
12 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 define constructor – Too generic to define real objects – Declare class with keyword abstract • Concrete class – Can instantiate objects – Provide specifics • Class hierarchies – Most general classes are usually abstract • Two. Dimensional. Shape - too generic to be concrete 2000 Prentice Hall, Inc. All rights reserved. 22
13 Polymorphism Example • 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 • Can use same superclass array as before - "fits right in" 2000 Prentice Hall, Inc. All rights reserved. 23
13 Polymorphism Example (II) • 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 2000 Prentice Hall, Inc. All rights reserved. 24
13 Polymorphism Example (III) • Iterator classes – Walks through all the objects in a container (such as an array) – Used in polymorphic programming • Walk through an array of superclass references • Call draw method for each reference 2000 Prentice Hall, Inc. All rights reserved. 25
14 New Classes and Dynamic Binding • Dynamic binding (late binding) – Accommodates new classes – Object's type does not need to be known at compile time – At execution time, method call matched with object 2000 Prentice Hall, Inc. All rights reserved. 26
15 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 hierarchy – Create an array of Shape references • Point them to various subclass objects • Call methods through the Shape reference 2000 Prentice Hall, Inc. All rights reserved. 27
1// Fig. 27. 4: Shape. java 2// Definition of abstract base class Shape Outline 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(); 1. abstract class Shape 8} 1. 1 Member functions 1. 2 abstract method get. Name 2000 Prentice Hall, Inc. All rights reserved.
9// Fig. 27. 4: Point. java 10 // Definition of class Point 11 12 public class Point extends Shape { 13 protected int x, y; // coordinates of the Point 14 15 // no-argument constructor 16 public Point() { set. Point( 0, 0 ); } 17 18 // constructor 19 public Point( int a, int b ) { set. Point( a, b ); } 20 21 // Set x and y coordinates of Point 22 public void set. Point( int a, int b ) 23 { 24 x = a; 25 y = b; 26 } 27 28 // get x coordinate 29 public int get. X() { return x; } 30 31 // get y coordinate 32 public int get. Y() { return y; } 33 34 // convert the point into a String representation 35 public String to. String() 36 { return "[" + x + ", " + y + "]"; } 37 38 // return the class name 39 public String get. Name() { return "Point"; } 40 } 2000 Prentice Hall, Inc. All rights reserved. Outline Class Point 1. point inherits from Shape 1. 1 protected data members 1. 2 Constructors 1. 3 New methods 1. 4 Overridden method get. Name
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 // Fig. 27. 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 ); } // Set radius of Circle public void set. Radius( double r ) { radius = ( r >= 0 ? r : 0 ); } // Get radius of Circle public double get. Radius() { return radius; } // Calculate area of Circle public double area() { return Math. PI * radius; } 2000 Prentice Hall, Inc. All rights reserved. Outline Class Circle 1. Inherits from point 1. 1 protected data member 1. 2 Constructors 1. 3 New methods 1. 4 Overridden method area
71 // convert the Circle to a String 72 public String to. String() Outline 73 { return "Center = " + super. to. String() + 74 "; Radius = " + radius; } 75 76 // return the class name 77 public String get. Name() { return "Circle"; } 1. 5 Overridden method to. String 78 78 } } 1. 6 Overridden method get. Name 2000 Prentice Hall, Inc. All rights reserved.
79 // Fig. 27. 10: Cylinder. java 80 // Definition of class Cylinder 81 82 public class Cylinder extends Circle { 83 protected double height; // height of Cylinder 84 85 // no-argument constructor 86 public Cylinder() 87 { 88 // implicit call to superclass constructor here 89 set. Height( 0 ); 90 } 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; 2000 Prentice Hall, Inc. All rights reserved. Outline Class Cylinder 1. inherit from Circle 1. 1 protected data member 1. 2 Constructors 1. 3 New methods 1. 4 Overridden method area
111 } 112 Outline 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. 5 Overridden method volume 1. 6 Overridden method to. String 1. 4 Overridden method get. Name 2000 Prentice Hall, Inc. All rights reserved.
123 // Fig. 27. 10: Test. java Outline 124 // Driver for point, circle, cylinder hierarchy 125 import javax. swing. JOption. Pane; 126 import java. text. Decimal. Format; 127 128 public class Test { Driver 129 public static void main( String args[] ) 130 { 1. import 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 ); 1. 1 Initialize objects 134 135 Shape array. Of. Shapes[]; 136 1. 2 Create Shape array 137 array. Of. Shapes = new Shape[ 3 ]; 138 139 // aim array. Of. Shapes[0] at subclass Point object 1. 3 Initialize array 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" + 2000 Prentice Hall, Inc. All rights reserved. 2. Call methods using objects
151 cylinder. get. Name() + ": " + cylinder. to. String(); 152 Outline 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 } 2000 Prentice Hall, Inc. All rights reserved. 2. 1 Call methods using array of references
Outline Program Output 2000 Prentice Hall, Inc. All rights reserved.
16 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 2000 Prentice Hall, Inc. All rights reserved. 37
16 Case Study: Creating and Using Interfaces (II) • 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 • Reexamine previous hierarchy – Replace abstract class Shape with interface Shape 2000 Prentice Hall, Inc. All rights reserved. 38
1// Fig. 27. 5: Shape. java 2// Definition of interface Shape Outline 3 4 public interface Shape { 5 public abstract double area(); 6 public abstract double volume(); 7 public abstract String get. Name(); 8} 2000 Prentice Hall, Inc. All rights reserved. Shape interface 1. abstract methods
9// Fig. 27. 5: Point. java 10 // Definition of class Point 11 12 public class Point extends Object implements Shape { 13 protected int x, y; // coordinates of the Point 14 15 // no-argument constructor 16 public Point() { set. Point( 0, 0 ); } 17 18 // constructor 19 public Point( int a, int b ) { set. Point( a, b ); } 20 21 // Set x and y coordinates of Point 22 public void set. Point( int a, int b ) 23 { 24 x = a; 25 y = b; 26 } 27 28 // get x coordinate 29 public int get. X() { return x; } 30 31 // get y coordinate 32 public int get. Y() { return y; } 33 34 // convert the point into a String representation 35 public String to. String() 36 { return "[" + x + ", " + y + "]"; } 37 38 // return the area 39 public double area() { return 0. 0; } 40 2000 Prentice Hall, Inc. All rights reserved. Outline Class Point 1. inherits from Object 1. 1 implements Shape 1. 2 protected data members 1. 3 Constructors 1. 4 New methods 1. 5 Define method area (required)
41 // return the volume 42 public double volume() { return 0. 0; } Outline 43 44 // return the class name 45 public String get. Name() { return "Point"; } 46 46 } } 1. 6 Define method volume (required) 1. 7 Define method get. Name (required) 2000 Prentice Hall, Inc. All rights reserved.
1// Fig. 27. 5: Circle. java 2// Definition of class Circle 3 4 public class Circle extends Point { // inherits from Point 5 protected double radius; 6 7 // no-argument constructor 8 public Circle() 9 { 10 // implicit call to superclass constructor here 11 set. Radius( 0 ); 12 } 13 14 // Constructor 15 public Circle( double r, int a, int b ) 16 { 17 super( a, b ); // call the superclass constructor 18 set. Radius( r ); 19 } 20 21 // Set radius of Circle 22 public void set. Radius( double r ) 23 { radius = ( r >= 0 ? r : 0 ); } 24 25 // Get radius of Circle 26 public double get. Radius() { return radius; } 27 28 // Calculate area of Circle 29 public double area() { return Math. PI * radius; } 30 2000 Prentice Hall, Inc. All rights reserved. Outline Class Circle 1. Inherits from Point Define class Circle as before
31 // convert the Circle to a String 32 public String to. String() 33 { return "Center = " + super. to. String() + 34 "; Radius = " + radius; } 35 36 // return the class name 37 public String get. Name() { return "Circle"; } 38 } 2000 Prentice Hall, Inc. All rights reserved. Outline
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 // Fig. 27. 5: 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 ); } // constructor public Cylinder( double h, double r, int a, int b ) { super( r, a, b ); // call superclass constructor 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; } // Calculate area of Cylinder (i. e. , surface area) public double area() { return 2 * super. area() + 2 * Math. PI * radius * height; 2000 Prentice Hall, Inc. All rights reserved. Outline Class Cylinder 1. Inherit from Circle Define class Cylinder as before
71 } 72 73 // Calculate volume of Cylinder 74 public double volume() { return super. area() * height; } 75 76 // Convert a Cylinder to a String 77 public String to. String() 78 { return super. to. String() + "; Height = " + height; } 79 80 // Return the class name 81 public String get. Name() { return "Cylinder"; } 82 } 2000 Prentice Hall, Inc. All rights reserved. Outline
83 // Fig. 27. 5: Test. java 84 // Driver for point, circle, cylinder hierarchy Outline 85 import javax. swing. JOption. Pane; 86 import java. text. Decimal. Format; 87 88 public class Test { 89 public static void main( String args[] ) 90 { 91 Point point = new Point( 7, 11 ); 92 Circle circle = new Circle( 3. 5, 22, 8 ); 93 Cylinder cylinder = new Cylinder( 10, 3. 3, 10 ); 94 95 Shape array. Of. Shapes[]; 96 97 array. Of. Shapes = new Shape[ 3 ]; 98 99 // aim array. Of. Shapes[0] at subclass Point object 100 array. Of. Shapes[ 0 ] = point; 101 102 // aim array. Of. Shapes[1] at subclass Circle object 103 array. Of. Shapes[ 1 ] = circle; 104 105 // aim array. Of. Shapes[2] at subclass Cylinder object 106 array. Of. Shapes[ 2 ] = cylinder; 107 108 String output = 109 point. get. Name() + ": " + point. to. String() + "n" + 110 circle. get. Name() + ": " + circle. to. String() + "n" + 2000 Prentice Hall, Inc. All rights reserved. Use same Driver as before
111 cylinder. get. Name() + ": " + cylinder. to. String(); 112 Outline 113 Decimal. Format precision 2 = new Decimal. Format( "#0. 00" ); 114 115 // Loop through array. Of. Shapes and print the name, 116 // area, and volume of each object. 117 for ( int i = 0; i < array. Of. Shapes. length; i++ ) { 118 output += "nn" + 119 array. Of. Shapes[ i ]. get. Name() + ": " + 120 array. Of. Shapes[ i ]. to. String() + 121 "n. Area = " + 122 precision 2. format( array. Of. Shapes[ i ]. area() ) + 123 "n. Volume = " + 124 precision 2. format( array. Of. Shapes[ i ]. volume() ); 125 } 126 127 JOption. Pane. show. Message. Dialog ( null, output, 128 "Demonstrating Polymorphism", 129 JOption. Pane. INFORMATION_MESSAGE ); 130 131 System. exit( 0 ); 132 } 133 } 2000 Prentice Hall, Inc. All rights reserved. Use same Driver as before
Outline Program Output (same as before) 2000 Prentice Hall, Inc. All rights reserved.
17 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 2000 Prentice Hall, Inc. All rights reserved. 49
17 Inner Class Definitions (II) • Windowed applications – We will execute an application in its own window (like an Applet) • Inherit from class JFrame (javax. swing) rather than JApplet – 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) 2000 Prentice Hall, Inc. All rights reserved. 50
17 Inner Class Definitions (III) • Event handling – Some class must implement interface Action. Listener • Must define method action. Performed • Class that implements Action. Listener "is an" Action. Listener – Method add. Action. Listener • Takes object of type Action. Listener • We can pass it an instance of the class that implements Action. Listener ("is a" relationship) • Example – We will use the Time class and execute an application in its own window – Use event handling to set the time 2000 Prentice Hall, Inc. All rights reserved. 51
1// Fig. 27. 6: Time. java 2// Time class definition 3 import java. text. Decimal. Format; // used for number formatting 4 5// This class maintains the time in 24 -hour format 6 public class Time extends Object { 7 private int hour; // 0 - 23 8 private int minute; // 0 - 59 9 private int second; // 0 - 59 10 11 // Time constructor initializes each instance variable 12 // to zero. Ensures that Time object starts in a 13 // consistent state. 14 public Time() { set. Time( 0, 0, 0 ); } 15 16 // Set a new time value using universal time. Perform 17 // validity checks on the data. Set invalid values to zero. 18 public void set. Time( int h, int m, int s ) 19 { 20 set. Hour( h ); // set the hour 21 set. Minute( m ); // set the minute 22 set. Second( s ); // set the second 23 } 24 25 // set the hour 26 public void set. Hour( int h ) 27 { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); } 28 29 // set the minute 30 public void set. Minute( int m ) 2000 Prentice Hall, Inc. All rights reserved. Outline Time class 1. import 1. 1 extends Object 1. 2 Data members 1. 3 Constructors 1. 4 Member methods
31 { minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); } 32 Outline 33 // set the second 34 public void set. Second( int s ) 35 { second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } 36 37 // get the hour 38 public int get. Hour() { return hour; } 39 40 // get the minute 41 public int get. Minute() { return minute; } 42 43 // get the second 44 public int get. Second() { return second; } 45 46 // 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 } 2000 Prentice Hall, Inc. All rights reserved. 1. 4 Member 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 89 90 // Fig. 27. 6: 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; private JButton exit. Button; public Time. Test. Window() { super( "Inner Class Demonstration" ); t = new Time(); Container c = get. Content. Pane(); // 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 ); minute. Label = new JLabel( "Set minute" ); minute. Field = new JText. Field( 10 ); 2000 Prentice Hall, Inc. All rights reserved. Outline 1. import 1. 1 extends JFrame 1. 2 Create GUI components in constructor 1. 3 Create instance of class that implements Action. Listener 1. 4 add. Action. Listener
91 minute. Field. add. Action. Listener ( handler ); 92 c. add( minute. Label ); 93 c. add( minute. Field ); 94 95 second. Label = new JLabel( "Set Second" ); 96 second. Field = new JText. Field( 10 ); 97 second. Field. add. Action. Listener ( handler ); 98 c. add( second. Label ); 99 c. add( second. Field ); 100 101 display = new JText. Field( 30 ); 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() 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(); 2000 Prentice Hall, Inc. All rights reserved. Outline 1. 5 Create GUI components 2. Methods 3. main
121 } 122 Outline 123 // Inner class definition for event handling 124 private class Action. Event. Handler implements Action. Listener { 125 public void action. Performed( Action. Event e ) 126 { 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( 131 Integer. parse. Int( e. get. Action. Command() ) ); 132 hour. Field. set. Text( "" ); 133 } 134 else if ( e. get. Source() == minute. Field ) { 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 } 2000 Prentice Hall, Inc. All rights reserved. 4. Inner class Action. Event. Handler implements Action. Listener
Outline Program Output 2000 Prentice Hall, Inc. All rights reserved.
17 Inner Class Definitions (IV) • 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 2000 Prentice Hall, Inc. All rights reserved. 58
17 Inner Class Definitions (IV) • Example my. Field. add. Action. Listener( new Action. Listener() { // anonymous inner class public void action. Performed( Action. Event e) { Actions } } ); – new creates an object – Action. Listener() begins definition of anonymous class and calls default constructor • Similar to public class my. Handler implements Action. Listener – Brace ( { ) begins class definition 2000 Prentice Hall, Inc. All rights reserved. 59
17 Inner Class Definitions (V) • Use the following code to allow the user to close windows using the close button window. add. Window. Listener( new Window. Adapter() { public void window. Closing( Window. Event e ) { System. exit( 0 ); } } ); 2000 Prentice Hall, Inc. All rights reserved. 60
18 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 – 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. Class. Name. Inner. Class. Name inner. Ref = ref. new Inner. Class. Name(); 2000 Prentice Hall, Inc. All rights reserved. 61
18 Notes on Inner Class Definitions (II) • Notes (continued) – Inner class can be static • Does not require object of outer class to be defined • Does not have access to outer class's non-static members 2000 Prentice Hall, Inc. All rights reserved. 62
- Slides: 62