Home › Java Tutorial › Java polymorphism
Java polymorphism
One call, many behaviours.
A variable of the parent type can hold any child object. Calling an overridden method runs the child's version. This lets one loop treat different objects the same way.
Example code
class Animal {
void speak() { System.out.println("..."); }
}
class Cat extends Animal {
void speak() { System.out.println("Meow"); }
}
class Dog extends Animal {
void speak() { System.out.println("Woof"); }
}
public class Main {
public static void main(String[] args) {
Animal[] pets = { new Cat(), new Dog(), new Animal() };
for (Animal p : pets) {
p.speak();
}
}
}