About

Polymorphism and Dynamic Dispatch

Polymorphism and Dynamic Dispatch

Polymorphism (“many forms”) allows a reference variable of a supertype to reference objects of any of its subtypes at runtime:

Animal myPet = new Dog();
myPet.makeSound(); // Invokes Dog's overridden makeSound()

Compile-Time vs Runtime Types

In the declaration above:

Dynamic Method Dispatch

When an overridden method is called, Java uses dynamic method dispatch (late binding) to execute the method belonging to the actual runtime object, not the declared variable type.

Overriding vs Overloading

Exercise 1

Given Animal a = new Cat();, what determines which method executes when a.eat() is invoked?

Show solution ↓
Solution

The actual runtime object type (Cat) determines which method executes via dynamic method dispatch.