Lesson 20 / 38

Polymorphism

Hold subtype objects through a supertype reference and let the JVM pick the overridden method at runtime via dynamic dispatch.

One reference, many types

A variable of a supertype can hold any subtype object. When you call an overridden method, the JVM dispatches to the actual object's version at runtime — not the reference type's.

In action

The loop below prints woof then meow even though every element is typed as Animal.

List<Animal> zoo = List.of(new Dog(), new Cat());
for (Animal a : zoo) System.out.println(a.sound());

Output:

woof
meow