Polymorphism
In short: The ability to call the same method call on different object types and get different behaviour depending on the actual object — “one interface, many forms”.
In more detail: A classic example: a list of different animal subclasses (dog, cat) is treated uniformly as “animal”, but a call to makeSound() runs each object’s own, overridden version. This is made possible by inheritance or by a shared interface that several classes implement without being related to each other.
In Depth
class Animal {
void makeSound() { System.out.println("..."); }
}
class Dog extends Animal {
void makeSound() { System.out.println("Woof!"); }
}
class Cat extends Animal {
void makeSound() { System.out.println("Meow!"); }
}
List<Animal> animals = List.of(new Dog(), new Cat());
for (Animal a : animals) {
a.makeSound(); // prints "Woof!" or "Meow!" - despite being the same call!
}The decisive point: the calling spot in the code (a.makeSound()) only knows at compile time that a is some Animal — WHICH concrete version of makeSound() actually runs is only decided at RUNTIME based on the actual object type (dynamic method binding). This allows adding new animal subclasses (e.g. Bird) without touching the loop code at all — it automatically works along, as long as the new class overrides the same method.
Roughly two kinds of polymorphism are distinguished:
- Inheritance-based polymorphism: a subclass overrides a method inherited from its superclass (see example above).
- Interface-based polymorphism: completely unrelated classes implement the same interface and are treated uniformly through it — e.g.
CarandBirdhave nothing in common except an interfaceMovablewith amove()method.
Polymorphism is the central mechanism that makes it possible to write open, extensible code (the “open/closed principle”: open for extension, closed for modification) — existing code doesn’t need to be touched for new requirements (new subclasses), as long as it consistently refers to the shared super-/interface level instead of concrete subclasses.
See also: Inheritance, Interface, OOP