Dynamic method dispatch is a key feature of runtime polymorphism in Java. It refers to the process where the appropriate method to be executed is determined at runtime based on the actual type of the object. This enables you to write more flexible and extensible code.
Here’s a step-by-step explanation of dynamic method dispatch:
- Method Overriding:
- Dynamic method dispatch is closely tied to method overriding. When a subclass provides a specific implementation for a method that is already defined in its superclass, it overrides the method.
class Animal {
void makeSound() {
System.out.println("Generic Animal Sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Bark");
}
}
Object Creation and Reference:
- Create an object of the subclass and assign it to a reference variable of the superclass type.
Animal myDog = new Dog();
- Here,
myDog
is declared as a reference of typeAnimal
, but it’s assigned an instance ofDog
. This is known as upcasting. - Method Invocation:
- Call the overridden method using the reference variable. The actual method that gets executed is determined at runtime based on the actual type of the object.
myDog.makeSound();
- In this example, the
makeSound
method from theDog
class will be invoked becausemyDog
refers to an instance ofDog
at runtime.
Here’s a more complete example:
class Animal {
void makeSound() {
System.out.println("Generic Animal Sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Bark");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.makeSound(); // Outputs: Bark
myCat.makeSound(); // Outputs: Meow
}
}
In this example, the makeSound
method is called on myDog
and myCat
objects, but the actual implementation that gets executed is determined by the runtime type of the objects (Dog
and Cat
respectively). This is dynamic method dispatch in action.