Junior — Middle
Can you explain the principle of dynamic method dispatch in object-oriented languages?
sobes.tech AI
Answer from AI
Dynamic method dispatch is a mechanism where the choice of which method implementation to invoke occurs at runtime, not at compile time. In object-oriented languages like Java, this allows calling overridden methods of subclasses through references to the base class.
Example:
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound(); // Will output "Bark" thanks to dynamic dispatch
}
}
Here, the sound() method is called on an object of type Dog, even though the variable a is of type Animal. The decision of which method to invoke is made at runtime, ensuring polymorphism and code flexibility.