Classes: Polymorphism (Part 4) : Sufian, Marini, Norleyza, Noor Faezah
Classes: Polymorphism (Part 4) : Sufian, Marini, Norleyza, Noor Faezah
Polymorphism(Part 4)
sufian, marini,
norleyza, noor faezah
Polymorphism
Java supports polymorphism.
The use of polymorphism can make a
program easier to maintain and extend.
To illustrate the concept of
polymorphism...
Polymorphism
Move!
Polymorphism
‘Poly’ + ‘morph’ + ism ability to be in
many forms / shapes
An object’s ability to decide what method
to apply itself, depending on where it is in
the inheritance hierarchy
Allows a single variable to refer to objects
from different classes
Polymorphism
Consider the following inheritance hierarchy:
Shape
void
display()
POLYMORPHISM The
display() method
class Application {
executed depends on
public static void main(String[ ] args) { the actual type of the
Shape shapes[] = new Shape[50]; receiver object.
shapes[0] = new Square(...);
shapes[1] = new IsoscelesTriangle(...);
shapes[2] = new Pentagon(...);
for (int i=0; i < 3; i++)
shapes[i].display();
}
}
For example..
class Rectangle {
…
public void display( ) { :Rectangle
… shapes
} display()
… :EquilateralTriangle
} display()
Shape
void
display()
Cat Tiger
public Animal(String n) {
name = n;
hungry = true;
}
clinic.listAnimals();
}
}