Beruflich Dokumente
Kultur Dokumente
Outline 27.1 27.2 27.3 27.4 27.5 27.6 27.7 27.8 27.9 27.10 27.11 27.12 27.13 27.14 27.15 27.16 27.17 27.18
Introduction Superclasses and Subclasses protected Members Relationship between Superclass Objects and Subclass Objects Implicit Subclass-Object-to-Superclass-Object Conversion Software Engineering with Inheritance Composition vs. Inheritance Introduction to Polymorphism Type Fields and switch Statements Dynamic Method Binding final Methods and Classes Abstract Superclasses and Concrete Classes Polymorphism Example 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
27.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
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
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
Using inheritance
Use keyword extends
class TwoDimensionalShape extends Shape{ ... } private members of superclass not directly accessible to subclass All other variables keep their member access
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.methodName
2000 Prentice Hall, Inc. All rights reserved.
27.4 Relationship between Superclass Objects and Subclass Objects Object of subclass
Can be treated as object of superclass
Reverse not true
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.
27.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.methodName
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. 27.3: Point.java // Definition of class Point public class Point { protected int x, y; // coordinates of the Point
Outline
1. Point definition
// No-argument constructor public Point() { // implicit call to superclass constructor occurs here setPoint( 0, 0 ); } // Constructor public Point( int a, int b ) { // implicit call to superclass constructor occurs here setPoint( a, b ); } // Set public { x = y = } x and y coordinates of Point void setPoint( int a, int b ) a; b;
31 32 33 34 35 36 37 } } 38 // 39 // 40
// get y coordinate public int getY() { return y; } // convert the point into a String representation public String toString() { return "[" + x + ", " + y + "]"; } Fig. 27.3: Circle.java Definition of class Circle // inherits from Point
Outline
1.2 Methods ---------------1. Circle Definition 1.1 extends Point 1.2 Multiple constructors
41 public class Circle extends Point { 42 protected double radius; 43 44 // No-argument constructor 45 public Circle() 46 { 47 48 49 50 51 52
// implicit call to superclass constructor occurs here setRadius( 0 ); } // Constructor public Circle( double r, int a, int b )
53 { 54 super( a, b ); // call to superclass constructor 55 setRadius( r ); 56 } 57 58 // Set radius of Circle 59 public void setRadius( double r ) 60 2000 Prentice { radius = ( All r rights >= 0.0 ? r : 0.0 ); } Hall, Inc. reserved.
61 62 63 64 65 66 67 68 69 70 // convert the Circle to a String public String toString() { // Calculate area of Circle public double area() { return Math.PI * radius * radius; } // Get radius of Circle public double getRadius() { return radius; }
Outline
71
72 73 74 } }
75 // Fig. 27.3: InheritanceTest.java 76 // Demonstrating the "is a" relationship 77 import java.text.DecimalFormat; 78 import javax.swing.JOptionPane; 79 80 public class InheritanceTest { 81 public static void main( String args[] ) 82 { 83 Point pointRef, p; 84 Circle circleRef, c; 85 String output; 86 87 p = new Point( 30, 50 ); 88 c = new Circle( 2.7, 120, 89 ); 89 90 output = "Point p: " + p.toString() + 91 "\nCircle c: " + c.toString(); 92 93 // use the "is a" relationship to refer to a Circle 94 // with a Point reference 95 pointRef = c; // assign Circle to pointRef 96 97 output += "\n\nCircle c (via pointRef): " + 98 pointRef.toString(); 99 100 // Use downcasting (casting a superclass reference to a 101 // subclass data type) to assign pointRef to circleRef 102 circleRef = (Circle) pointRef; 103 104 output += "\n\nCircle c (via circleRef): " + 105 circleRef.toString(); 2000 Prentice Hall, Inc. All rights reserved.
Outline
1. Initialize objects 2. Refer to a subclass object with a superclass reference 2.1 toString 2.2 Downcast 2.3 toString
106 107 108 DecimalFormat precision2 = new DecimalFormat( "0.00" ); output += "\nArea of c (via circleRef): " +
Outline
109
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 } } } else
precision2.format( circleRef.area() );
3. if statement
output += "\n\np does not refer to a Circle"; JOptionPane.showMessageDialog( null, output, "Demonstrating the \"is a\" relationship", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 );
Outline
Program Output
Superclass
Specifies commonality Look for commonality among a set of classes
"Factor it out" to form the superclass
Example
Employee is a BirthDate; Employee has a Birthdate; //Wrong! //Composition
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
Example
Triangle, Circle, and Square all subclasses of Shape
Each has an overridden draw method
27.12 Abstract Superclasses and Concrete Classes Abstract classes (abstract superclasses)
Sole purpose is to be a superclass
Other classes inherit from it
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
TwoDimensionalShape - too generic to be concrete
2000 Prentice Hall, Inc. All rights reserved.
27.13
Polymorphism Example
Class Quadrilateral
Rectangle "is a" Quadrilateral getPerimeter method can be performed on any subclass
Square, Parallelogram, Trapezoid Same method takes on "many forms" - polymorphism
27.13
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
27.13
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
1 3 4 5 6 7 8
Outline
1. abstract class Shape 1.1 Member functions 1.2 abstract method getName
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 40
// Fig. 27.4: Point.java // Definition of class Point public class Point extends Shape { protected int x, y; // coordinates of the Point
Outline
Class Point
// no-argument constructor public Point() { setPoint( 0, 0 ); } // constructor public Point( int a, int b ) { setPoint( a, b ); } // Set public { x = y = } x and y coordinates of Point void setPoint( int a, int b ) a; b;
1. point inherits from Shape 1.1 protected data members 1.2 Constructors 1.3 New methods 1.4 Overridden method getName
// get x coordinate public int getX() { return x; } // get y coordinate public int getY() { return y; } // convert the point into a String representation public String toString() { return "[" + x + ", " + y + "]"; } // return the class name public String getName() { return "Point"; } } 2000 Prentice Hall, Inc. All rights reserved. }
41 // Fig. 27.10: Circle.java 42 // Definition of class Circle 43 44 public class Circle extends Point { // inherits from Point 45 protected double radius; 46 47 // no-argument constructor 48 public Circle() 49 { 50 // implicit call to superclass constructor here 51 setRadius( 0 ); 52 } 53 54 // Constructor 55 public Circle( double r, int a, int b ) 56 { 57 super( a, b ); // call the superclass constructor 58 setRadius( r ); 59 } 60 61 // Set radius of Circle 62 public void setRadius( double r ) 63 { radius = ( r >= 0 ? r : 0 ); } 64 65 // Get radius of Circle 66 public double getRadius() { return radius; } 67 68 // Calculate area of Circle 69 public double area() { return Math.PI * radius * radius; } 70 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 72 73 74 75 76 77 78 } }
// convert the Circle to a String public String toString() { return "Center = " + super.toString() + "; Radius = " + radius; } // return the class name public String getName() { return "Circle"; }
Outline
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 setHeight( 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 setHeight( h ); 97 } 98 99 // Set height of Cylinder 100 public void setHeight( double h ) 101 { height = ( h >= 0 ? h : 0 ); } 102 103 // Get height of Cylinder 104 public double getHeight() { 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
Outline
// Calculate volume of Cylinder public double volume() { return super.area() * height; } // Convert a Cylinder to a String public String toString() { return super.toString() + "; Height = " + height; }
1.5 Overridden method volume 1.6 Overridden method toString 1.4 Overridden method getName
120 // Return the class name 121 public String getName() { return "Cylinder"; } 122 } }
123 // Fig. 27.10: Test.java 124 // Driver for point, circle, cylinder hierarchy 125 import javax.swing.JOptionPane; 126 import java.text.DecimalFormat; 127 128 public class Test { 129 130 131 132 133 public static void main( String args[] ) { Point point = new Point( 7, 11 ); Circle circle = new Circle( 3.5, 22, 8 ); Cylinder cylinder = new Cylinder( 10, 3.3, 10, 10 );
Outline
Driver 1. import 1.1 Initialize objects 1.2 Create Shape array 1.3 Initialize array 2. Call methods using objects
134 135
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 String output = point.getName() + ": " + point.toString() + "\n" + // aim arrayOfShapes[2] at subclass Cylinder object arrayOfShapes[ 2 ] = cylinder; // aim arrayOfShapes[1] at subclass Circle object arrayOfShapes[ 1 ] = circle; // aim arrayOfShapes[0] at subclass Point object arrayOfShapes[ 0 ] = point; arrayOfShapes = new Shape[ 3 ];
Shape arrayOfShapes[];
circle.getName() + ": " + circle.toString() + "\n" + 2000 Prentice Hall, Inc. All rights reserved.
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 } } }
Outline
DecimalFormat precision2 = new DecimalFormat( "0.00" ); // Loop through arrayOfShapes and print the name, // area, and volume of each object. for ( int i = 0; i < arrayOfShapes.length; i++ ) { output += "\n\n" + arrayOfShapes[ i ].getName() + ": " + arrayOfShapes[ i ].toString() + "\nArea = " + precision2.format( arrayOfShapes[ i ].area() ) + "\nVolume = " + precision2.format( arrayOfShapes[ i ].volume() );
Outline
Program Output
Using interfaces
Class specifies it uses interface with keyword implements
Multiple interfaces use comma-separated list
27.16 Case Study: Creating and Using Interfaces (II) Using interfaces (continued)
Interfaces used in place of abstract classes
Used when no default implementation
Previous interfaces
We have used interface ActionListener Required to define actionPerformed
1 2 3
Outline
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() { setPoint( 0, 0 ); } 17 18 // constructor 19 public Point( int a, int b ) { setPoint( a, b ); } 20 21 // Set x and y coordinates of Point 22 public void setPoint( int a, int b ) 23 { 24 x = a; 25 y = b; 26 } 27 28 // get x coordinate 29 public int getX() { return x; } 30 31 // get y coordinate 32 public int getY() { return y; } 33 34 // convert the point into a String representation 35 public String toString() 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 42 43 44 45 46 } }
// return the volume public double volume() { return 0.0; } // return the class name public String getName() { return "Point"; }
Outline
1.6 Define method volume (required) 1.7 Define method getName (required)
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 setRadius( 0 ); 12 } 13 14 // Constructor 15 public Circle( double r, int a, int b ) 16 { 17 super( a, b ); // call the superclass constructor 18 setRadius( r ); 19 } 20 21 // Set radius of Circle 22 public void setRadius( double r ) 23 { radius = ( r >= 0 ? r : 0 ); } 24 25 // Get radius of Circle 26 public double getRadius() { return radius; } 27 28 // Calculate area of Circle 29 public double area() { return Math.PI * radius * radius; } 30 2000 Prentice Hall, Inc. All rights reserved.
Outline
Class Circle 1. Inherits from Point Define class Circle as before
31
32
33 34 35 36 37 38 }
Outline
39 // Fig. 27.5: Cylinder.java 40 // Definition of class Cylinder 41 42 public class Cylinder extends Circle { 43 protected double height; // height of Cylinder 44 45 // no-argument constructor 46 public Cylinder() 47 { 48 // implicit call to superclass constructor here 49 setHeight( 0 ); 50 } 51 52 // constructor 53 public Cylinder( double h, double r, int a, int b ) 54 { 55 super( r, a, b ); // call superclass constructor 56 setHeight( h ); 57 } 58 59 // Set height of Cylinder 60 public void setHeight( double h ) 61 { height = ( h >= 0 ? h : 0 ); } 62 63 // Get height of Cylinder 64 public double getHeight() { return height; } 65 66 // Calculate area of Cylinder (i.e., surface area) 67 public double area() 68 { 69 return 2 * super.area() + 70 2 * Math.PI * radius * height; 2000 Prentice Hall, Inc. All rights reserved.
Outline
71 72 73 74
Outline
// Calculate volume of Cylinder public double volume() { return super.area() * height; } // Convert a Cylinder to a String public String toString()
75
76 77
78
79 80 81 82 }
83 // Fig. 27.5: Test.java 84 // Driver for point, circle, cylinder hierarchy 85 import javax.swing.JOptionPane; 86 import java.text.DecimalFormat; 87 88 public class Test { 89 90 91 92 93 public static void main( String args[] ) { Point point = new Point( 7, 11 ); Circle circle = new Circle( 3.5, 22, 8 ); Cylinder cylinder = new Cylinder( 10, 3.3, 10, 10 );
Outline
94 95
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 String output = point.getName() + ": " + point.toString() + "\n" + // aim arrayOfShapes[2] at subclass Cylinder object arrayOfShapes[ 2 ] = cylinder; // aim arrayOfShapes[1] at subclass Circle object arrayOfShapes[ 1 ] = circle; // aim arrayOfShapes[0] at subclass Point object arrayOfShapes[ 0 ] = point; arrayOfShapes = new Shape[ 3 ];
Shape arrayOfShapes[];
circle.getName() + ": " + circle.toString() + "\n" + 2000 Prentice Hall, Inc. All rights reserved.
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 } } }
Outline
DecimalFormat precision2 = new DecimalFormat( "#0.00" ); // Loop through arrayOfShapes and print the name, // area, and volume of each object. for ( int i = 0; i < arrayOfShapes.length; i++ ) { output += "\n\n" + arrayOfShapes[ i ].getName() + ": " + arrayOfShapes[ i ].toString() + "\nArea = " + precision2.format( arrayOfShapes[ i ].area() ) + "\nVolume = " + precision2.format( arrayOfShapes[ i ].volume() );
Outline
27.17
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
27.17
Windowed applications
We will execute an application in its own window (like an Applet)
Inherit from class JFrame (javax.swing) rather than JApplet
27.17
Event handling
Some class must implement interface ActionListener
Must define method actionPerformed Class that implements ActionListener "is an" ActionListener
Method addActionListener
Takes object of type ActionListener We can pass it an instance of the class that implements ActionListener ("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.
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
Outline
Time class 1. import 1.1 extends Object 1.2 Data members 1.3 Constructors 1.4 Member methods
// 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 // Time constructor initializes each instance variable // to zero. Ensures that Time object starts in a // consistent state. public Time() { setTime( 0, 0, 0 ); } // Set a new time value using universal time. Perform // validity checks on the data. Set invalid values to zero. public void setTime( int h, int m, int s ) { setHour( h ); // set the hour setMinute( m ); // set the minute setSecond( s ); // set the second } // set the hour public void setHour( int h ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); } // set the minute public void setMinute( int m ) 2000 Prentice Hall, Inc. All rights reserved.
31 32 33 34 35 36 37 38 39 40 41 42 43
Outline
// set the second public void setSecond( int s ) { second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } // get the hour public int getHour() { return hour; } // get the minute public int getMinute() { return minute; } // get the second
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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
// Fig. 27.6: TimeTestWindow.java // Demonstrating the Time class set and get methods import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TimeTestWindow extends JFrame { private Time t; private JLabel hourLabel, minuteLabel, secondLabel; private JTextField hourField, minuteField, secondField, display; private JButton exitButton; public TimeTestWindow() { super( "Inner Class Demonstration" ); t = new Time();
Outline
1. import 1.1 extends JFrame 1.2 Create GUI components in constructor 1.3 Create instance of class that implements ActionListener 1.4 addActionListener
Container c = getContentPane();
// create an instance of the inner class ActionEventHandler handler = new ActionEventHandler(); c.setLayout( new FlowLayout() ); hourLabel = new JLabel( "Set Hour" ); hourField = new JTextField( 10 ); hourField.addActionListener( handler ); c.add( hourLabel ); c.add( hourField ); minuteLabel = new JLabel( "Set minute" ); minuteField = new JTextField( 10 );
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
minuteField.addActionListener( handler ); c.add( minuteLabel ); c.add( minuteField ); secondLabel = new JLabel( "Set Second" ); secondField = new JTextField( 10 ); secondField.addActionListener( handler ); c.add( secondLabel ); c.add( secondField ); display = new JTextField( 30 ); display.setEditable( false ); c.add( display ); exitButton = new JButton( "Exit" ); exitButton.addActionListener( handler ); c.add( exitButton ); } public void displayTime() { display.setText( "The time is: " + t ); } public static void main( String args[] ) { TimeTestWindow window = new TimeTestWindow(); window.setSize( 400, 140 ); window.show();
Outline
121 122 123 124 125 126 127 128 129 130 131
Outline
// Inner class definition for event handling private class ActionEventHandler implements ActionListener { public void actionPerformed( ActionEvent e ) { if ( e.getSource() == exitButton ) System.exit( 0 ); t.setHour( Integer.parseInt( e.getActionCommand() ) ); // terminate the application else if ( e.getSource() == hourField ) {
132 133
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 } } } } }
hourField.setText( "" ); }
else if ( e.getSource() == minuteField ) { t.setMinute( Integer.parseInt( e.getActionCommand() ) ); minuteField.setText( "" ); else if ( e.getSource() == secondField ) { t.setSecond( Integer.parseInt( e.getActionCommand() ) ); secondField.setText( "" );
displayTime();
Outline
Program Output
27.17
27.17
Example
myField.addActionListener( new ActionListener() { // anonymous inner class public void actionPerformed( ActionEvent e) { Actions } } );
new creates an object ActionListener() begins definition of anonymous class and calls default constructor
Similar to public class myHandler implements ActionListener
27.17
Use the following code to allow the user to close windows using the close button
window.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } );
27.18
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