Dynamic Method Dispatch
1. Dynamic method dispatch is a technique by which call to a overridden method is resolved at runtime, rather than compile time.
2. When an overridden method is called by a reference, then which version of overridden method is to be called is decided at runtime according to the type of object it refers.
3. Dynamic method dispatch is performed by JVM not compiler. Dynamic method dispatch allows java to support overriding of methods and perform runtime polymorphism.
4. It allows subclasses to have common methods and can redefine specific implementation for them. This lets the superclass reference respond differently to same method call depending on which object it is pointing.
Example:
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
}
}
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
The output from the program is shown here:
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method
0 Comments