Dynamic method dispatch is a mechanism in which the override method that will be called for a particular object is determined at runtime rather than compile time. (more on Compile Time VS Runtime). This enables polymorphism, where objects of different classes can be treated as objects of a common super type (upcasting is involved in this process), this enables flexible and reusable code. The super type can be both concrete class, abstract class or interface. In dynamic method dispatch, the type of the reference variable can be different from the type of the actual object it refers to.
Example 1: Concrete super type
// the concrete super class Animal
class Animal {
void makeSound() {
System.out.println("Some generic sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog();
// Implicit upcasting
// Animal myAnimal = (Animal) new Dog();
myAnimal.makeSound(); // Dynamic method dispatch
}
}
Bark
In this example, Animal
is a superclass and Dog
is its subclass. By upcasting a Dog
object to an Animal
reference, we enable dynamic method dispatch.
When myAnimal.makeSound()
is called, Java determines at runtime which makeSound
method to execute (Animal
or Dog
). Since myAnimal
is actually a Dog
object, the makeSound
method in the Dog
class is called.
Example 2: Abstract super type
interface Animal {
void makeSound();
}
class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
}
class Cat implements Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog();
myAnimal.makeSound(); // dynamic method dispatch
}
}
Bark
In this example, the Animal
is an interface, and Dog
is a class that implements the interface. This allows you to treat a Dog
object as an Animal
and you can invoke the defined makeSound()
method through Animal
reference. Since the Dog
is the actual object, the makeSound()
method of the Dog
class is invoked.
Dynamic method dispatch with abstract class or interface is an important technique that is used extensively in the design patterns and programming practices.
Back to parent page: Java Standard Edition (Java SE) and Java Programming
Web_and_App_Development Programming_Languages Java Dynamic_Method_Dispatch Runtime_Polymorphism Upcasting