inheritance & polymorphism1. 2 introduction besides composition, another form of reuse is...
TRANSCRIPT
Inheritance & Polymorphism 1
Inheritance & Polymorphism
Inheritance & Polymorphism 2
Introduction
Besides composition, another form of reuse is inheritance.With inheritance, an object can inherit behavior from another object, thus reusing its code.The class inheriting is called a subclass (or derived class).The class inherited from is called a superclass (or base class).
Inheritance & Polymorphism 3
Subclass
A subclass usually adds to its superclass, thus creating a more specialized object.A subclass may be the superclass for its own subclass, thus creating a class hierarchy.The immediate superclass for a subclass is called its direct superclass.A superclass above the direct superclass is called an indirect superclass.In Java, the Object class is a direct or indirect superclass to all other classes.
Inheritance & Polymorphism 4
Multiple Inheritance
Java, unlike C++, does not support multiple inheritance (Java allows only one direct superclass).Java uses interfaces to provide some of this capability.With an interface, multiple classes can support some of the same behavior.
Inheritance & Polymorphism 5
Inheritance Relationships
Inheritance is known as an “is-a relationship”.Composition is a “has-a relationship”.A car is a vehicle.A car has a steering wheel.
Inheritance & Polymorphism 6
Protected Members
If a member is given the “protected” access modifier, then subclasses of that class may access it, as well as classes in the same package:
Specifier
Class Subclass
Package
World
Public x x x x
Protected
x x x
package x x
private x
Inheritance & Polymorphism 7
Inheritance & Polymorphism
Inheritance is a form of software reusability in which new classes are created from existing classes by
absorbing their attributes and behaviours and enhance these, with capabilities the new classes require.
Polymorphism enables us to write programs (and methods) in a general fashion
to handle a wide variety of existing and yet-to-be-specified related classes.
makes it easy to add new capabilities to a system.
Inheritance and Polymorphism are effective techniques for dealing with software complexity.
Inheritance & Polymorphism 8
Polymorphism
Polymorphism means many forms.In object-oriented programming, a method of a superclass may be implemented in many different ways by its subclasses.Thus, a command may have many different forms.Polymorphism allows programs to similarly process different objects of the same superclass.Suppose for example a class animal has subclasses of fish, frog, and bird.The superclass defines a move method, but each specific animal may move in a different way.
Inheritance & Polymorphism 9
Animal
Fish Frog Bird
Superclass definesmove method
Each subclass implements move methodin its own way
Programmer can send the “move” message to eachobject without regard to which object it is.
Inheritance & Polymorphism 10
Polymorphism
Polymorphism makes it possible to design and implement systems that are more easily extensible.Programs can be written to process generically – as superclass objects – objects of all existing classes in a hierarchy.Classes that do not exist during program development can be added with little or no modifications to the generic part of the program (as long as those classes are part of the hierarchy that is being processed generically).The only parts of a program that need modification are those parts that require direct knowledge of the particular class that is added to the hierarchy.We will look at two class hierarchies later on…..
Inheritance & Polymorphism 11
PolymorphismThe next example illustrates inheritance and polymorphism.When the “toString” method is called, Java performs dynamic binding (or late binding) which determines the method to call at runtime by examining which object is making the call, rather than at compile-time by only considering the reference type.
Inheritance & Polymorphism 12
Point, Circle Example (1)public class Point {
protected int x, y; // coordinates of the Point
public Point()
{
setPoint( 0, 0 );
}
public Point( int a, int b )
{
setPoint( a, b );
}
Inheritance & Polymorphism 13
Point, Circle Example (1a)public void setPoint( int a, int b )
{
x = a;
y = b;
}
public int getX() { return x; }
public int getY() { return y; }
public String toString()
{
return "[" + x + ", " + y + "]";
}
}
Inheritance & Polymorphism 14
Point, Circle Example (2)public class Circle extends Point
{
// inherits from Point
protected double radius;
public Circle()
{
// implicit call to superclass constructor
setRadius( 0 );
}
public Circle( double r, int a, int b )
{
super( a, b ); // call to superclass constructor
setRadius( r );
}
Inheritance & Polymorphism 15
Point, Circle Example (2a)public void setRadius( double r )
{
radius = ( r >= 0.0 ? r : 0.0 );
}
public double getRadius() { return radius; }
public double area()
{
return Math.PI * radius * radius;
}
public String toString()
{
return "Center = " + "[" + x + ", " + y + "]" + "; Radius = " + radius;
}
}
Inheritance & Polymorphism 16
Point, Circle Example (3)import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class Tester {
public static void main( String args[] )
{
Point pointRef, p;
Circle circleRef, c;
String output;
p = new Point( 30, 50 );
c = new Circle( 2.7, 120, 89 );
output = "Point p: " + p.toString() + "\nCircle c: " + c.toString();
// use the "is a" relationship to refer to a Circle
// with a Point reference
pointRef = c; // assign Circle to pointRef
output += "\n\nCircle c (via pointRef): " + pointRef.toString();
Polymorphism & Dynamic Binding
Inheritance & Polymorphism 17
Point, Circle Example (4)// Use downcasting (casting a superclass reference to a subclass data type) to assign pointRef to circleRef
circleRef = (Circle) pointRef;
output += "\n\nCircle c (via circleRef): " + circleRef.toString();
DecimalFormat precision2 = new DecimalFormat( "0.00" );
output += "\nArea of c (via circleRef): " + precision2.format( circleRef.area() );
// Attempt to refer to Point object with Circle reference
if ( p instanceof Circle ) {
circleRef = (Circle) p;
output += "\n\ncast successful";
}
else
output += "\n\np does not refer to a Circle";
JOptionPane.showMessageDialog( null, output,"Demonstrating the \"is a\" relationship",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
Inheritance & Polymorphism 18
Point, Circle Example (5)
Inheritance & Polymorphism 19
Case Study - Point,Circle,Cylinder
Suppose a set of shape classes such as Circle, Triangle , Square etc. are all derived from superclass Shape, and each class has the ability to draw itself (has its own draw() method,which would be different in each case).When drawing a shape, whatever shape it might be, it would be nice to be able to treat all these shapes generically as objects of the superclass Shape.Then to draw any shape, we could call the draw() method of superclass Shape and let the program determine dynamically (at run time) which subclass draw() method should be called (depending on the objects type).To enable this kind of behaviour, we declare draw() in the superclass, and override draw() in each of the subclasses to draw the appropriate shape.
Inheritance & Polymorphism 20
abstract
An abstract method is not actually implemented in the class. The body of the method is implemented in subclasses of that class.
public abstract void draw();
An abstract method must be part of an abstract class. public abstract class Shape extends Object
Abstract classes cannot be instantiated. It is a compile-time error to try something like
Shape m = new Shape();
where Shape has been declared to be abstract
Inheritance & Polymorphism 21
Abstract Classes
A variable of an abstract type can refer to an object of a subclass of that type.This permits polymorphism.Sometimes a collection, such as an array, of a superclass or abstract superclass type contains objects of subclasses.An iterator is used to traverse all objects in the collection.A message sent to each object behaves in a polymorphic manner.
Inheritance & Polymorphism 22
Case Study : Point,Circle,Cylinder (1)
public abstract class Shape extends Object
{
public double area()
{return 0.0;}
public double volume()
{return 0.0;}
public abstract String getName();
public abstract void Draw();
}
Inheritance & Polymorphism 23
Case Study : Point,Circle,Cylinder (2)
import javax.swing.JOptionPane;
public class Point extends Shape
{
protected int x, y; // coordinates of the Point
public Point(){ setPoint( 0, 0 ); }
public Point( int a, int b ){ setPoint( a, b ); }
public void setPoint( int a, int b )
{
x = a;
y = b;
}
Inheritance & Polymorphism 24
Case Study : Point,Circle,Cylinder (3)
public int getX() { return x; }
public int getY() { return y; }
public String toString()
{ return "[" + x + ", " + y + "]"; }
public String getName(){ return "Point"; }
public void Draw()
{ JOptionPane.showMessageDialog(null,getName() + ": " + this);
}
}
Inheritance & Polymorphism 25
Case Study : Point,Circle,Cylinder (4)
import javax.swing.JOptionPane;
public class Circle extends Point { // inherits from Point
protected double radius;
public Circle(){
// implicit call to superclass constructor
setRadius( 0 );
}
public Circle( double r, int a, int b ){
super( a, b ); // call to superclass constructor
setRadius( r );
}
public void setRadius( double r )
{ radius = ( r >= 0.0 ? r : 0.0 ); }
Inheritance & Polymorphism 26
Case Study : Point,Circle,Cylinder (5)
public double getRadius() { return radius; }
public double area() { return Math.PI * radius * radius; }
public String toString()
{
return "Center = " + "[" + x + ", " + y + "]" +
"; Radius = " + radius;
}
public String getName()
{ return "Circle"; }
public void Draw()
{
JOptionPane.showMessageDialog(null,getName() + ": " + this);
}
}
Inheritance & Polymorphism 27
Case Study : Point,Circle,Cylinder (6)
import javax.swing.JOptionPane;
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 );
}
Inheritance & Polymorphism 28
Case Study : Point,Circle,Cylinder (7)
// 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;
}
Inheritance & Polymorphism 29
Case Study : Point,Circle,Cylinder (8)
// 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"; }
public void Draw()
{ JOptionPane.showMessageDialog(null,getName() + ": " + this);
}
}
Inheritance & Polymorphism 30
Case Study : Point,Circle,Cylinder (9)
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class Tester {
public static void main( String args[] )
{
String output;
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 ];
Inheritance & Polymorphism 31
Case Study : Point,Circle,Cylinder (10)
// 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;
point.Draw();
circle.Draw();
cylinder.Draw();
DecimalFormat precision2 = new DecimalFormat( "0.00" );
Inheritance & Polymorphism 32
Case Study : Point,Circle,Cylinder (11)
// Loop through arrayOfShapes and print the name,
// area, and volume of each object.
for ( int i = 0; i < arrayOfShapes.length; i++ )
{
arrayOfShapes[ i ].Draw();
output = "\nArea = " + precision2.format( arrayOfShapes[ i ].area() ) +
"\nVolume = " + precision2.format( arrayOfShapes[ i ].volume() );JOptionPane.showMessageDialog( null, output,"Demonstrating Polymorphism", JOptionPane.INFORMATION_MESSAGE );
}
System.exit( 0 );
}
}
Polymorphism & Dynamic Binding
Inheritance & Polymorphism 33
Case Study : Notes (12)
Superclass Shape extends Object and consists of 3 public methods and contains no data (although it could).
getName() & Draw() are abstract so they are overridden in each of the subclasses
area() & volume() are overridden in subclasses when it is appropriate for those classes to have a different area/volume calculation
Class Point is derived from Shape . area() & volume() are inherited (not overridden) from Shape getName() & Draw() are implementations of the abstract methods in the
superclass. If either of these methods were not defined, class Point would itself be an abstract class.
Inheritance & Polymorphism 34
Case Study : Notes (13)
Class Circle is derived from Point area() is overridden as the area is different to that of a Point &
volume() is inherited because a Circle has no volume getName() & Draw() are implementations of the abstract methods
in the superclass. If either of these methods were not defined here, the Point version of these methods would be inherited.
Class Cylinder is derived from Circle area() is overridden as the area is different to that of a Circle &
volume() is overridden because a Cylinder has a volume getName() & Draw() are implementations of the abstract methods
in the superclass. If either of these methods were not defined here, the Circle version of these methods would be inherited.
In each class new methods are added specific to that class
Inheritance & Polymorphism 35
Interfaces (1)
Interfaces provide some features of multiple inheritance:
Like an abstract class, an interface defines a set of methods (and perhaps constants as well), but no implementation.
By using the implements keyword, a class can indicate that it implements that set of methods.
This makes it unnecessary for related classes to share a common superclass or to directly subclass object.
It’s possible for a class to implement several interfaces.
Inheritance & Polymorphism 36
Interfaces (3)
An interface is like a class with nothing but abstract methods and final, static fields. All methods and fields of an interface must be public.However, unlike a class, an interface can be added to a class that is already a subclass of another class. Furthermore an interface can apply to members of many different classesWhen you introduce a new class, you can choose to “support” any number of interfacesFor each interface you support you must implement member functions defined in the interface
Inheritance & Polymorphism 37
Final
If a method is declared “final”, it cannot be overridden in a subclass.All subclass calls to a final method would call the superclass method.Therefore, this binding can be done at compile time rather than runtime.This permits inlining to be performed by the compiler for simple methods.
Inheritance & Polymorphism 38
Final
If a class is declared final, it cannot be subclassed.One reason for doing this is for security purposes.For example, the “String” class in Java is final, so that it cannot be subclassed such that its security features are bypassed.
Inheritance & Polymorphism 39
Interfaces
Sometimes different classes need common functionality.Such cases are supported by creating an “interface”.An interface specifies a set of methods to support but does not provide implementation.Interfaces only contain constants and abstract methods.
Inheritance & Polymorphism 40
Interfaces
All interface members are public.Methods are abstract.Constants are static and final.Generally, the keywords public, abstract, static and final are not used in an interface declaration since they will have these characteristics by default.
Inheritance & Polymorphism 41
Interfaces
To use an interface, a class “implements” the interface.Each interface method must be declared in the (concrete) class that implements the interface using the same signature.Using interfaces lets very different objects behave in a polymorphic way.
Inheritance & Polymorphism 42
InterfacesA class can inherit from only one direct superclass, but it can implement multiple interfaces.
public class MyClass extends MySuper implements IFace1, IFace2, IFace3, …
An interface can be used when there is no implementation to inherit.If a class implements an interface but not all of its methods, it must be an abstract class.Interface methods are implicitly abstract.Interfaces are defined in their own .java file named with the interface name.
Inheritance & Polymorphism 43
Interfaces
When a class implements an interface, the is-a relationship applies.If Employee implements interface Payable, an Employee is-a Payable.Payable may be used as a type to refer to any object that implements it.This permits passing an object to a Payable parameter, or setting a Payable reference to an object.
Inheritance & Polymorphism 44
<<interface>>Payable
Invoice Employee
Italics indicate Employeeis an abstract class.
The next example uses this class hierarchy.
SalariedEmployee
Inheritance & Polymorphism 45
// Payable.java// Payable interface declaration.
public interface Payable { double getPaymentAmount(); // calculate payment; no
implementation} // end interface Payable
Inheritance & Polymorphism 46
this and superA subclass inherits the methods of its super class. When a subclass overrides such methods, it’s often necessary to invoke the equivalent method in the parent class and the keyword super lets you do this:
class mybutton extends Button { public void setLabel(String label) { setFont(myspecialfont); // change the font super.setLabel(label); // label the button }}
Note that in a constructor any invocation of a superclass constructor must be the first statement - if not present:
super();is added by the compiler.The keyword this refers to the current object - useful when you want to pass the current object to another to allow the latter to execute the former’s methods.
Inheritance & Polymorphism 47
instanceof
If a superclass reference is used, it may refer to objects of its subclasses.If it is necessary to know which particular subclass an object belongs to, the instanceof operator can be used.
Button b;MyButton mb; // where MyButton extends Button
if (b instanceof Button) // is trueif (mb instanceof MyButton) // is trueif (mb instanceof Button) // is trueif (b instanceof MyButton) // is false
Inheritance & Polymorphism 48
Downcasting
If a superclass variable refers to a subclass object, methods of the superclass can be called which behave polymorphically (dynamic-binding).However, attempting to call a subclass method from a superclass reference results in a compile error unless the superclass reference is downcast to the subclass.
Inheritance & Polymorphism 49
Downcasting
A subclass variable can be assigned to a superclass variable since a subclass is-a superclass.However, assigning a superclass variable to a subclass variable is a compile error without casting.Such casting is called “downcasting” since a higher type is cast to a lower type.
superclass var = subclass var // ok because of is-asubclass var = superclass var // requires downcast
Inheritance & Polymorphism 50
Inheritance Principles
Common operations and fields belong to a superclassUse inheritance to model the is-a relationshipDon’t use inheritance unless ALL inherited methods make sense.Use Polymorphism not type information