Professional Documents
Culture Documents
Inheritance and Polymorphism
Inheritance and Polymorphism
Inheritance and Polymorphism
Polymorphism
1
Inheritance
Object-oriented programming allows you to define new
classes from existing classes.
This is called inheritance.
Inheritance is an important and powerful feature for reusing
software.
Suppose you need to define classes to model circles,
rectangles, and triangles.
These classes have many common features.
What is the best way to design these classes so as to avoid
redundancy and make the system easy to comprehend and
easy to maintain?
The answer is to use inheritance.
2
Superclasses and Subclasses
4
Superclasses and Subclasses
The Circle class inherits all accessible data fields and methods
from the GeometricObject class.
In addition, it has a new data field, radius, and its associated
get and set methods.
5
Superclasses and Subclasses
The Rectangle class inherits all accessible data fields and
methods from the GeometricObject class.
In addition, it has the data fields width and height and their
associated get and set methods.
6
Superclasses and Subclasses
7
Example 1:
GeometricObject Superclass
Import java.util.Date;
public class GeometricObject {
private String color = "white";
private boolean filled;
private Date dateCreated;
/** Construct a default geometric object */
public GeometricObject() {
dateCreated = new Date();
}
/** Construct a geometric object with the specified color
* and filled value */
public GeometricObject(String color, boolean filled) {
dateCreated = new Date();
this.color = color;
this.filled = filled;
}
/** Return color */
public String getColor() {
return color;
}
public Circle() {
}
13
Rectangle Subclass
public class Rectangle extends GeometricObject {
public Rectangle() {
}
16
Rectangle Subclass
The following code creates objects of Circle and Rectangle
and invokes the methods on these objects.
17
TestCircleRectangle Class
public class TestCircleRectangle {
public static void main(String[] args) {
using
inheritance
superclass
Animal
subclass
String name
subclass String getName()
Dog Cat
int fleas int hairballs
int getFleas() int getHairballs()
void speak() void speak()
Animal Superclass
public class Animal {
public Animal(String n) {
name = n;
}
27
Using the super Keyword
1. Calling Superclass Constructors
Unlike properties and methods, the constructors of a superclass
are not inherited by a subclass.
They can only be invoked from the constructors of the
subclasses using the keyword super.
The syntax to call a superclass’s constructor is:
super(), or super(parameters);
The statement super() invokes the no-arg constructor of its
superclass, and the statement super(arguments) invokes the
superclass constructor that matches the arguments.
The statement super() or super(arguments) must appear in the
first line of the subclass’s constructor; this is the only way to
explicitly invoke a superclass constructor.
28
Using the super Keyword
For example:
29
Using the super Keyword
2. Constructor Chaining
A constructor may invoke an overloaded constructor or its
superclass constructor.
If neither is invoked explicitly, the compiler automatically puts
super() as the first statement in the constructor. For example:
30
Using the super Keyword
public class Faculty extends Employee {
public static void main(String[] args){
new Faculty();
}
public Faculty(){
System.out.println("(4) Performs Faculty's tasks");
}
}
class Employee extends Person{
public Employee(){
this("(2) Invoke Employee's overloaded constructor");
System.out.println("(3) Performs Employee's tasks ");
}
32
Using the super Keyword
33
Using the super Keyword
3. Calling Superclass Methods
The keyword super can also be used to reference a method other
than the constructor in the superclass. The syntax is:
super.method(parameters);
You could rewrite the printCircle() method in the Circle class
as follows:
public void printCircle() {
System.out.println("The circle is created " + super.getDateCreated() +
" and the radius is " + radius);
}
It is not necessary to put super before getDateCreated() in this
case, however, because getDateCreated is a method in the
GeometricObject class and is inherited by the Circle class.
34
The protected Data Field and Methods
35
The protected Data Field and Methods
36
The protected Data Field and Methods
37
The protected Data Field and Methods
38
Overriding Methods
39
Overriding Methods
The toString method in the GeometricObject class returns
the string representation of a geometric object.
To override it, add the following new method in the Circle
class.
40
Overriding Methods
public class Circle extends GeometricObject
{
// Other methods are omitted
41
Overriding Methods
42
Overriding Methods
Several points are worth noting:
An instance method can be overridden only if it is accessible.
Thus a private method cannot be overridden, because it is not
accessible outside its own class.
If a method defined in a subclass is private in its superclass, the two
SuperClassName.staticMethodName.
43
Overriding vs. Overloading
44
Overriding vs. Overloading
Let us use an example to show the differences between
overriding and overloading.
In (a) below, the method p(double i) in class A overrides the
same method defined in class B.
In (b), however, the class A has two overloaded methods:
p(double i) and p(int i) .
The method p(double i) is inherited from B.
45
Overriding vs. Overloading
46
Overriding vs. Overloading
When you run the Test class in (a), both a.p(10) and a.p(10.0)
invoke the p(double i) method defined in class A to display
10.0.
When you run the Test class in (b), a.p(10) invokes the p(int
i) method defined in class A to display 10, and a.p(10.0)
invokes the p(double i) method defined in class B to display
20.0.
47
Overriding vs. Overloading
Note:
Overridden methods are in different classes related by
inheritance; overloaded methods can be either in the same class
or different classes related by inheritance.
48
Overriding vs. Overloading
To avoid mistakes, you can use a special Java syntax, called
override annotation, to place @Override before the method in the
subclass.
For example:
@Override
public String toString() {
return super.toString() + "\nradius is " +
radius;
}
}
49
Polymorphism
50
Polymorphism
Polymorphism means that a variable of a supertype can refer
to a subtype object.
A class defines a type. A type defined by a subclass is called a
subtype, and a type defined by its superclass is called a
supertype.
Therefore, you can say that Circle is a subtype of
GeometricObject and GeometricObject is a supertype for
Circle.
The inheritance relationship enables a subclass to inherit
features from its superclass with additional new features.
51
Polymorphism
A subclass is a specialization of its superclass; every instance
of a subclass is also an instance of its superclass, but not vice
versa.
52
Polymorphism
public class PolymorphismDemo {
/** Main method */
public static void main(String[] args){
// Display circle and rectangle properties
Circle c1 = new Circle(1, "red", false)
displayObject(c1);
Rectangle r = new Rectangle(1, 1, "black", true);
displayObject(r);
}
/** Display geometric object properties */
public static void displayObject(GeometricObject object)
{
System.out.println("Created on " +
object.getDateCreated()+". Color is “ +
object.getColor());
}
}
53
Polymorphism
The method displayObject takes a parameter of the
GeometricObject type.
You can invoke displayObject by passing any instance of
GeometricObject (e.g., new
Circle(1, "red", false) and new Rectangle(1, 1, "black",
false) .
An object of a subclass can be used wherever its superclass
object is used.
This is commonly known as polymorphism
In simple terms, polymorphism means that a variable of a
supertype can refer to a subtype object.
54