Polymorphism
Prerequisites: Inheritance
A variable declared as a parent type can refer to any subtype object, and calling an overridden method runs the subtype's version — decided at runtime, not at compile time.
Animal[] animals = { new Dog("Rex"), new Cat("Tom") };
for (Animal a : animals) {
a.makeSound(); // runs Dog's or Cat's version, whichever it is
}
Rex barks
Tom meows
This is what makes it possible to write a method that accepts
Animal and have it correctly handle any current or future subclass,
without an if/instanceof chain for every kind.
Common mistakes
- Writing
if (a instanceof Dog) { ... } else if (a instanceof Cat)chains to work around not overriding a method properly — usually a sign the method should be overridden onAnimalinstead.