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

Method Overriding and the Most Specific Implementation

How the JVM always invokes the most specific (lowest in hierarchy) overridden method for the runtime type.

Method Overriding and the Most Specific Implementation

What you'll learn: How the JVM chooses which method to call when multiple overridden versions exist in a class hierarchy.


When you have a superclass reference pointing to a subclass object, and you call an overridden method, the JVM doesn't just look at the reference type—it looks at the actual object at runtime and invokes the most specific (lowest in the hierarchy) implementation.

The Core Rule

The JVM always executes the method from the runtime type (the actual object), not the compile-time type (the reference). If a method is overridden at multiple levels in the inheritance chain, the version in the most derived class wins.

How It Works

Think of it like asking a family tree "Who can answer this question?" When you call a method, the JVM starts at the actual object's class and searches upward. The first matching method it finds (closest to the actual object) is the one that executes.

Example:

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

class Dog extends Animal {
    @Override
    void speak() { System.out.println("Bark"); }
}

class Beagle extends Dog {
    @Override
    void speak() { System.out.println("Arooo"); }
}

Animal ref = new Beagle();
ref.speak();  // Output: "Arooo"

Even though ref is declared as Animal, the runtime type is Beagle. The JVM finds speak() in Beagle—the most specific implementation—and calls it, ignoring the versions in Dog and Animal.

Key Takeaway: The JVM always invokes the most specific (lowest in the hierarchy) overridden method based on the runtime type of the object, ensuring that the actual object's behavior is always used.