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:

  • Compile-Time Type (Declared Type): Animal. The compiler verifies that makeSound() is a valid method on Animal.
  • Runtime Type (Actual Type): Dog. At runtime, the JVM inspects the actual object on the heap.

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

  • Method Overriding: Subclass supplies a specific implementation of a method declared in its supertype with identical name and parameter types (@Override).
  • Method Overloading: Methods within the same class share the same name with different parameter signatures, resolved at compile time.
Exercise 1
Question

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.