Polymorphism in Java
Polymorphism means a variable declared as a superclass type can refer to an object of any of its subclasses, and calling a method through that variable runs whichever version the object's actual, real class defines — not necessarily the version belonging to the variable's declared type. Animal a = new Dog(); is entirely legal, and a.makeSound() runs Dog's version of makeSound if Dog overrides it, even though a is declared as an Animal.
This is what makes it possible to write one method that accepts an Animal parameter and have it correctly handle a Dog, a Cat, or any other Animal subclass passed to it, each behaving according to its own actual type. The calling code doesn't need to know or check which specific subclass it received at all.
A superclass reference to a subclass object
Animal a = new Dog(); is legal, since a Dog genuinely is an Animal.
Which version actually runs
Calling a method through a depends on the object's real, actual class, not on how a happens to be declared.
Overridden methods are what makes this useful
If Dog overrides a method Animal declares, calling that method through an Animal-typed reference to a Dog still runs Dog's version.
One method, many behaviors
A method parameter typed as a superclass can accept any subclass, each responding to the same call in its own way.
The calling code stays generic
Code written against the superclass type never needs to check or care which specific subclass it actually received.
class Animal { void makeSound() { System.out.println("Some generic sound"); }} class Dog extends Animal { void makeSound() { System.out.println("Woof!"); }} public class PolymorphismDemo { public static void main(String[] args) { Animal a = new Dog(); a.makeSound(); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.