Java Programming Inheritance and Polymorphisim Object-Oriented Programming Inheritance: –...
Transcript of Java Programming Inheritance and Polymorphisim Object-Oriented Programming Inheritance: –...
Java: Object-Oriented Programming
Inheritance:
– superclasses and subclasses
Polymorphism:
– abstract and concrete classes
Dynamic binding
Multiple inheritance via Interfaces and
implementations
What is Inheritance?
Object:
– Data attributes; Methods behavior
Object that inherits: data and methods already
available from “parent” class
Inheritance hierarchy
– entire “lineage” of objects in a parent/child structure
Is-A: object inheritance implements the is-a
relationship,
– similar to animal classification (a dog is-a mammal)
Why Use Subclasses?
Reuse of code
If subclasses do not redefine a superclass
method, the superclass method is used
Compound data structures of a variety of
objects (i.e., array) can be constructed
Object categories with conceptual
relationships can be associated together via
hierarchy
Superclasses and Subclasses
Applet is a superclass which is typically extended, so
is Object
Is-A relationships: inheritance. Has-A relationships:
composition
Example: Shape Class Hierarchy // Fig. 9.4: Point.java
// Definition of class Point
public class Point {
protected int x, y; // coordinates of the Point
// 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 x and y coordinates of Point
public void setPoint( int a, int b )
{
x = a;
y = b;
}
// 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 + "]"; }
}
// Fig. 9.4: 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 occurs here
setRadius( 0 );
}
// Constructor
public Circle( double r, int a, int b )
{
super( a, b ); // call to superclass constructor
setRadius( r );
}
// Set radius of Circle
public void setRadius( double r )
{ radius = ( r >= 0.0 ? r : 0.0 ); }
// Get radius of Circle
public double getRadius() { return radius; }
// Calculate area of Circle
public double area() { return Math.PI * radius * radius; }
// convert the Circle to a String
public String toString()
{
return "Center = " + "[" + x + ", " + y + "]" +
"; Radius = " + radius;
}
}
Inheritance Hierarchy
Use the extends keyword: public class Circle extends Point { // inherits from Point
Circle Class
Point class
Is-A (inheritance)
int x
int y Protected instance variables
Point ()
Point (int a, int b) constructors
Public methods
void setPoint (int a, int b)
int getX ()
int getY ()
String toString ()
Double radius Protected instance variables
Circle ()
Circle (double r, int a, int b) constructors
void setRadius( double r )
double getRadius()
double area()
String toString()
Public methods Is-A
Notes
Constructors are never inherited
Subclass constructors must always invoke a superclass constructor first via the super call
– (it is a syntax error not to do this)
Syntax error: subclass methods with the same signature as a
superclass method but with different return types
public Circle (double r, int a, int b) {
super (a, b);
setRadius (r);
System.out.println (“Circle
constructor: “ + “toString());
}
Notes
Subclass can access public and protected members
of the superclass
Subclass cannot access the private members of the
superclass
Superclass methods can be overridden when those
methods are inappropriate for a subclass object
Access parent methods: super.x
– super.super.x is a syntax error
– Be careful: can cause infinite recursion.
Conversion Up and Down the Inheritance Hierarchy
Default: one-way road
– Superclass objects cannot reference subclass-only elements
An object of a subclass can be treated as an object of
its corresponding superclass. The reverse is not true
(without an explicit cast)
An explicit cast can make an object to be treated as a
subclass object
If a cast is attempted and the target (at execution
time) is not a subclass object, an exception
(classCastException) is thrown
Second Example: Inheritance // 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;
System.out.println( "Point constructor: " + this );
}
// finalizer
protected void finalize()
{
System.out.println( "Point finalizer: " + this );
}
// convert the point into a String representation
public String toString()
{ return "[" + x + ", " + y + "]"; }
}
// 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 );
}
// finalizer
protected void finalize()
{
System.out.println( "Circle finalizer: " + this );
super.finalize(); // call superclass finalize method
}
// convert the Circle to a String
public String toString()
{
return "Center = " + super.toString() +
"; 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 circle1, circle2;
circle1 = new Circle( 4.5, 72, 29 );
circle2 = new Circle( 10, 5, 5 );
circle1 = null; // mark for garbage collection
circle2 = null; // mark for garbage collection
System.gc(); // call the garbage collector
}
}
Polymorphism
The ability to appear in many forms
OOP specific: A programming language's ability to process objects differently depending on their data type or class.
To avoid code like this:
If shape object OBJ is a rectangle
then area = …
else If shape object OBJ is a cylinder
then area = …
else ...
Abstract and Concrete Classes
Abstract classes
– Define common methods
– Cannot be instantiated
Concrete classes (Java default)
– Must implement common methods
– can be instantiated
Concrete is the default
Abstract Classes
Representational tool:
Inheritance hierarchy can be unified via abstract classes
Machine independence:
Objects and required methods can be defined and
requirements can be set without dependence on platform
Multiple inheritance (interfaces): special functionality can
be created for objects to implement via the interface
concept
Abstract Classes and Polymorphism
Generic classes:
Complete hierarchies can be processed without reference to
specifics
Polymorphism:
“Many shapes” can be manipulated by the same named
methods
Extendibility:
New objects, methods and functionality can easily be added
to a hierarchy without impacting large pieces of code
Example: Shapes
Abstract superclass shape defines the
abstract method getName()
// Fig. 9.10: Shape.java
// Definition of abstract base class Shape
public abstract class Shape extends Object {
public double area() { return 0.0; }
public double volume() { return 0.0; }
public abstract String getName();
}
// Fig. 9.10: Point.java
// Definition of class Point
public class Point extends Shape {
protected int x, y; // coordinates of the Point
// no-argument constructor
public Point() { setPoint( 0, 0 ); }
// constructor
public Point( int a, int b ) { setPoint( a, b ); }
// Set x and y coordinates of Point
public void setPoint( int a, int b )
{
x = a;
y = b;
}
// 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"; }
// 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
setRadius( 0 );
}
// Constructor
public Circle( double r, int a, int b )
{
super( a, b ); // call the superclass constructor
setRadius( r );
}
// Set radius of Circle
public void setRadius( double r )
{ radius = ( r >= 0 ? r : 0 ); }
// Get radius of Circle
public double getRadius() { return radius; }
// Calculate area of Circle
public double area() { return Math.PI * radius * radius; }
// convert the Circle to a String
public String toString()
{ return "Center = " + super.toString() +
"; Radius = " + radius; }
// return the class name
public String getName() { return "Circle"; }
}
// 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
setHeight( 0 );
}
// constructor
public Cylinder( double h, double r, int a, int b )
{
super( r, a, b ); // call superclass constructor
setHeight( h );
}
// Set height of Cylinder
public void setHeight( double h )
{ height = ( h >= 0 ? h : 0 ); }
// Get height of Cylinder
public double getHeight() { return height; }
// 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 a Cylinder to a String
public String toString()
{ return super.toString() + "; Height = " + height; }
// Return the class name
public String getName() { return "Cylinder"; }
}
// Fig. 9.10: Test.java
// Driver for point, circle, cylinder hierarchy
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class Test {
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 );
Shape arrayOfShapes[];
arrayOfShapes = new Shape[ 3 ];
// aim arrayOfShapes[0] at subclass Point object
arrayOfShapes[ 0 ] = point;
// aim arrayOfShapes[1] at subclass Circle object
arrayOfShapes[ 1 ] = circle;
// aim arrayOfShapes[2] at subclass Cylinder object
arrayOfShapes[ 2 ] = cylinder;
String output =
point.getName() + ": " + point.toString() + "\n" +
circle.getName() + ": " + circle.toString() + "\n" +
cylinder.getName() + ": " + cylinder.toString();
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() );
}
JOptionPane.showMessageDialog( null, output,
"Demonstrating Polymorphism",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
Interfaces and Implementations
Interfaces are used in place of abstract classes when
a class hierarchy does not contain the methods in the
interface; it is a way to provide multiple inheritance
Multiple inheritance versus interfaces and
implementation
Interface definition contains a set of public abstract
methods
An object which implements an interface must define
every method in the interface
Interfaces
a named collection of method definitions and variable
declarations:
– All methods must be abstract (without mplementations).
– All variables must be static final
Features interface abstract class
Multiple
inheritance
A class may implement
several interfaces.
A class may extend only one abstract
class.
Default
Implementation
An interface cannot
provide any code at all,
An abstract class can provide complete
code, default code
Overloading A class must overload all
methods.
Optional for classes inherited
Interface vs. Abstract Class
My new
Object
Thread
Object
Event
Object
Abstract
Class
Is-A
Inheritance
Polymorphism
Interfaces
Multiple “Inheritance”
extends
implements
Example: Creating and Using Interfaces
// Fig. 9.11: Shape.java
// Definition of interface Shape
public interface Shape {
public abstract double area();
public abstract double volume();
public abstract String getName();
}
// 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() { setPoint( 0, 0 ); }
// constructor
public Point( int a, int b ) { setPoint( a, b ); }
// Set x and y coordinates of Point
public void setPoint( int a, int b )
{
x = a;
y = b;
}
// 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 area
public double area() { return 0.0; }
// return the volume
public double volume() { return 0.0; }
// return the class name
public String getName() { return "Point"; }
}
// Fig. 9.11: 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
setRadius( 0 );
}
// Constructor
public Circle( double r, int a, int b )
{
super( a, b ); // call the superclass constructor
setRadius( r );
}
// Set radius of Circle
public void setRadius( double r )
{ radius = ( r >= 0 ? r : 0 ); }
// Get radius of Circle
public double getRadius() { return radius; }
// Calculate area of Circle
public double area() { return Math.PI * radius * radius; }
// convert the Circle to a String
public String toString()
{ return "Center = " + super.toString() +
"; Radius = " + radius; }
// return the class name
public String getName() { return "Circle"; }
}
// Fig. 9.11: 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
setHeight( 0 );
}
// constructor
public Cylinder( double h, double r, int a, int b )
{
super( r, a, b ); // call superclass constructor
setHeight( h );
}
// Set height of Cylinder
public void setHeight( double h )
{ height = ( h >= 0 ? h : 0 ); }
// Get height of Cylinder
public double getHeight() { return height; }
// 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 a Cylinder to a String
public String toString()
{ return super.toString() + "; Height = " + height; }
// Return the class name
public String getName() { return "Cylinder"; }
}
// Fig. 9.11: Test.java
// Driver for point, circle, cylinder hierarchy
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class Test {
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 );
Shape arrayOfShapes[];
arrayOfShapes = new Shape[ 3 ];
// aim arrayOfShapes[0] at subclass Point object
arrayOfShapes[ 0 ] = point;
// aim arrayOfShapes[1] at subclass Circle object
arrayOfShapes[ 1 ] = circle;
// aim arrayOfShapes[2] at subclass Cylinder object
arrayOfShapes[ 2 ] = cylinder;
String output =
point.getName() + ": " + point.toString() + "\n" +
circle.getName() + ": " + circle.toString() + "\n" +
cylinder.getName() + ": " + cylinder.toString();
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() ); }
JOptionPane.showMessageDialog( null, output,
"Demonstrating Polymorphism",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 ); }
}
44
Object Class
Class Object methods
– clone
– equals
– finalize
– getClass
– hashCode
– notify, notifyAll, wait
– toString
Clone
45
Protected
– No argument
– Return an object reference
Default: shallow copy
Typical Override: Deep copy
equals
46
Usage: object1.equals(object2)
Default: using references to see if they are
the same object
False: if one argument is null
True: comparison to itself
If (a == b) then (b==a)
If (a == b && b= c) then (a == c)
More Methods
hashCode
ToString
– Default: the package name and class name,
followed by a hexadecimal representation of the
value returned by the object’s hashCode method
notify, notifyAll
– Related to multi-threading
48
49
(Optional) GUI and Graphics Case Study: Displaying Text and Images Using Labels
Labels
– Display information and instructions
– JLabel
Display a single line of text
Display an image
Display both text and image
50 Outline
LabelD
emo.ja
va (1 of 2)
Line 13
Line 16
Line 19
Line 25
1 // Fig 9.19: LabelDemo.java
2 // Demonstrates the use of labels.
3 import java.awt.BorderLayout;
4 import javax.swing.ImageIcon;
5 import javax.swing.JLabel;
6 import javax.swing.JFrame;
7
8 public class LabelDemo
9 {
10 public static void main( String args[] )
11 {
12 // Create a label with plain text
13 JLabel northLabel = new JLabel( "North" );
14
15 // create an icon from an image so we can put it on a JLabel
16 ImageIcon labelIcon = new ImageIcon( "GUItip.gif" );
17
18 // create a label with an Icon instead of text
19 JLabel centerLabel = new JLabel( labelIcon );
20
21 // create another label with an Icon
22 JLabel southLabel = new JLabel( labelIcon );
23
24 // set the label to display text (as well as an icon)
25 southLabel.setText( "South" );
26
Change the text the
southLabel
displays
ImageIcon constructor
argument specifies the
path to the image
Declare and initialize
centerLabel with a
JLabel that displays the
labelIcon
Create a JLabel that
displays the string
“North”
51 Outline
LabelD
emo.ja
va (2 of 2)
Lines 34-36
27 // create a frame to hold the labels
28 JFrame application = new JFrame();
29
30 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
31
32 // add the labels to the frame; the second argument specifies
33 // where on the frame to add the label
34 application.add( northLabel, BorderLayout.NORTH );
35 application.add( centerLabel, BorderLayout.CENTER );
36 application.add( southLabel, BorderLayout.SOUTH );
37
38 application.setSize( 300, 300 ); // set the size of the frame
39 application.setVisible( true ); // show the frame
40 } // end main
41 } // end class LabelDemo
Attach the labels to the
JFrame at north, center and
south