Dynamic Method Dispatch or Late Binding or Runtime Polymorphism in Java
https://en.wikipedia.org/wiki/Dynamic_dispatch
What is Dispatch ?
It simply means “determining which method to call”.
What is Dynamic Dispatch ?
The “dynamic” part simply says that it is determined at runtime. That is, the method to be called is determined at runtime.
With inheritance / polymorphism we don’t know the concrete runtime type of an expression, thus which method to be called must be “dynamically” determined during runtime.
Dynamic Method Dispatch or Runtime Polymorphism in Java
Java uses a technique for method invocation called “dynamic dispatch”.
NOTE: In Java, we can override methods only, not the variables(data members), so runtime polymorphism cannot be achieved by data members.
public class A {
int x = 10;
public void draw() {
System.out.println("A is drawing");
}
public void spin() {
System.out.println("A is spinning");
}
}
public class B extends A {
int x = 20;
public void draw() {
System.out.println("B is drawing");
}
public void bad() {
System.out.println("B is bad");
}
}
public class TestDriver {
public static void main(String[] args) {
A testObject = new B();
System.out.println("x: " + testObject.x); // 10
testObject.draw(); // calls B's draw, polymorphic
testObject.spin(); // calls A's spin, inherited by B
// compiler error, you are manipulating this as an A
// testObject.bad();
}
}
Then we see that B inherits spin from A. However, when we try to manipulate the object as if it were a type A, we still get B’s behavior for draw. The draw behavior is polymorphic.
Method overriding
- Method overriding is one of the ways in which Java supports Runtime Polymorphism. Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time.
- When an overridden method
draw()is called through a superclass reference, Java determines which version(superclass/subclasses) of that method is to be executed based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time. - At run-time, it depends on the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed
- A superclass reference variable can refer to a subclass object. This is also known as upcasting.
- Java uses this fact to resolve calls to overridden methods at run time.
Benefits
- Dynamic method dispatch allow Java to support overriding of methods which is central for run-time polymorphism.
- It allows a class to specify methods that will be common to all of its derivatives, while allowing subclasses to define the specific implementation of some or all of those methods.
- It also allow subclasses to add its specific methods subclasses to define the specific implementation of some.