Java Dynamic Method Dispatch

Learn how Java resolves overridden methods at runtime using reference types and object instances.

The Golden Dispatch Rule:

Reference Type (Type on the left) determines what methods are accessible at compile time.
Actual Object Type (Type on the right) determines which implementation runs at runtime.

📜 Core Rules of Dispatch

  1. Reference Assignment
    A superclass reference can refer to a subclass object: SuperClass obj = new SubClass();
  2. Runtime Resolution
    When an overridden method is called, Java inspects the actual object on the heap at runtime (not the reference type) to decide which method version to execute.
  3. Compile-Time Constraint
    You can only call methods that exist in the reference type class. If a method exists only in the child class, calling it using a parent reference causes a compilation error.

💻 Class Hierarchy Code

class Animal {
    void makeSound() {
        System.out.println("Some generic sound");
    }
}

class Dog extends Animal {
    void makeSound() {
        System.out.println("Woof! Woof!");
    }
}

class Cat extends Animal {
    void makeSound() {
        System.out.println("Meow! Meow!");
    }
}

⚙️ Dynamic Dispatch Simulator

Select an object type to instantiate under the Animal reference, then dispatch makeSound().

Stack Memory (Compile Time)
Reference Name: myAnimal
Reference Type: Animal
⬇️ Points to object on Heap at runtime
Heap Memory (Runtime)
Actual Instance: new Animal()
Resolved Method: Animal.makeSound()
> Console Output will appear here when you click "myAnimal.makeSound();"