Course contentsShow
← Java
Lesson 442 of 2,87011. Polymorphism and Dynamic DispatchFree lesson

Dynamic Dispatch with Upcast References

Seeing how overridden methods execute subclass implementations even through superclass references.

Dynamic Dispatch with Upcast References

You'll learn how overridden methods execute subclass implementations even through superclass references.

When you upcast a subclass object to a superclass reference, Java still remembers what the object really is. This means when you call an overridden method through that superclass reference, Java executes the subclass's version, not the superclass's version.

The Core Idea

Think of it like sending a letter. Even if you address someone by their formal title (superclass reference), they still respond as themselves (subclass behavior). The reference type determines what methods you can call, but the actual object type determines which implementation runs.

This mechanism is called dynamic dispatch or runtime polymorphism because Java decides which method to execute at runtime based on the actual object, not the reference type.

How It Works

class Animal {
    void makeSound() {
        System.out.println("Generic animal sound");
    }
}

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

// Upcasting to Animal reference
Animal myAnimal = new Dog();

// Calls Dog's makeSound(), not Animal's!
myAnimal.makeSound();  // Output: "Woof!"

Even though myAnimal is declared as Animal, the actual object is a Dog. When makeSound() is called, Java looks at the real object type and executes Dog's overridden version.

This only works for overridden methods. If you try to call a method that only exists in Dog, the compiler prevents it because the reference type is Animal.

Key Takeaway: Dynamic dispatch ensures that overridden methods execute the subclass implementation, even when called through a superclass reference—the actual object's type determines which method runs, not the reference type.