MJ#27: Dynamic Method Dispatch in Java

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:

  1. 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();

  1. Here, myDog is declared as a reference of type Animal, but it’s assigned an instance of Dog. This is known as upcasting.
  2. 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();

  1. In this example, the makeSound method from the Dog class will be invoked because myDog refers to an instance of Dog 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.

Leave a comment