What is dynamic method dispatch in Java?

Dynamic Method Dispatch is the mechanism through which Java determines which overridden method should be executed at runtime rather than at compile time. It is a key feature of Runtime Polymorphism and allows a parent class reference to invoke methods of a child class object.

Key Points: • Dynamic Method Dispatch is the foundation of Runtime Polymorphism in Java. • Method selection is based on the actual object type, not the reference type. • It works only with overridden methods, not overloaded methods. • The decision about which method to execute is made during runtime. • It enables flexible and extensible application design.

Example: Suppose Animal is the parent class and Dog is the child class. If a parent class reference points to a Dog object, Java executes the Dog's version of the overridden method at runtime.

Code Example:

class Animal {

    void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {

    @Override
    void makeSound() {
        System.out.println("Dog barks");
    }
}

class Cat extends Animal {

    @Override
    void makeSound() {
        System.out.println("Cat meows");
    }
}

public class Demo {

    public static void main(String[] args) {

        Animal animal1 = new Dog();
        Animal animal2 = new Cat();

        animal1.makeSound();
        animal2.makeSound();
    }
}

Output:

Dog barks Cat meows

How It Works:

1. The reference type is Animal. 2. The actual objects are Dog and Cat. 3. At runtime, JVM checks the actual object type. 4. The corresponding overridden method is executed.

Benefits:

• Supports Runtime Polymorphism • Improves flexibility and extensibility • Reduces tight coupling between classes • Makes code easier to maintain and enhance

Interview Tip: A concise interview answer is:

"Dynamic Method Dispatch is the process by which Java resolves overridden method calls at runtime. When a parent class reference points to a child class object, the JVM executes the method belonging to the actual object type, enabling Runtime Polymorphism."