Dynamic Method Dispatch
Dynamic Method Dispatch
In Java, when a class inherits from another class (subclass inherits from superclass), a superclass
variable can hold a reference to an object of its subclass. This is because a subclass object is also
considered an object of its superclass [This is the reason behind restrictions of constructor]. It
inherits all the members (variables and methods) defined in the superclass, along with any new
members it defines itself.
Here's an example:
Java
class Animal {
public void makeSound() {
System.out.println("Generic animal sound");
}
}
In this example:
Reference Variables
A reference variable is a variable that stores a memory address. It acts like a pointer, indicating
where the actual object resides in memory. When you create an object using new, the object is
allocated memory, and a reference variable holds the address of that memory location.
When you call a method on a superclass reference variable that points to a subclass object,
dynamic method dispatch comes into play. This means that the actual method that gets executed
is determined at runtime based on the object's actual type (subclass). In the example:
Key Points: