Professional Documents
Culture Documents
9 - Polymorphism
9 - Polymorphism
Nurochman
Polymorphism
• From poly (many) + morph (form)
• The ability for a method to behave differently
depending on the object it is called upon.
Polymorphism
• Overloaded methods
Same name, but different input or output, e.g.
public double distance (int x, int y);
public double distance (Point p);
• Overriden methods – Redefined in a subclass
with the same signature (same input, same
output)
Overriding Methods
• Methods in subclass may have same name,
parameters and return type as methods in the
superclass
• Overriding methods effectively replace
superclass methods for instances of the
subclass
Feline Class
class Feline {
boolean vocal = true;
void makeNoise(){
System.out.println("Non-specific cat sound");
}
void call() {
System.out.println("Puss, Puss, Puss……");
if (vocal) {
makeNoise();
}
}
void quiet() {
vocal = false;
}
}
Lion and Moggy
class Lion extends Feline {
void makeNoise(){
System.out.println("Roar! Roar!");
}
}