In this article we will look at dynamic method dispatch in Java which is a way to provide run-time polymorphism.
What is dynamic method dispatch?
Dynamic method dispatch is a mechanism which resolves the call to a overridden method at run-time based on the type of object being referred.
When is dynamic method dispatch possible?
It is possible only when the following are satisfied:
- A class inherits from another class (inheritance)
- Super class variable refers a sub class object
- A overridden method is invoked using the super class reference
Why dynamic method dispatch?
Dynamic method dispatch is the way to provide run-time polymorphism in Java. Let’s look at what is static (compile-time) polymorphism and dynamic (run-time) polymorphism.
Before understanding what is the difference between static and dynamic polymorphism, let’s look at what is method binding. The process of associating or linking a method call with its definition (body) is known as method binding. This is can take place in two ways: at compile time or at run-time.
When method binding takes place at compile time it is known as static binding and if the method binding takes place at run-time it is known as dynamic binding. Static binding takes place when there is no inheritance or if there is inheritance and the method is specified as static or final or private, or if the type of reference and type of the object it is referring to are same. In all other cases it will be dynamic binding.
Now, if the call to a polymorphic method (overloaded or overridden) is bound at compile time, it is known as static polymorphism or else if the call to a polymorphic method takes place at run-time it is known as dynamic polymorphism.
Run-time polymorphism always depends on the type of sub class object that is being referred to by the super class reference. This type of binding is also known as late binding.
Now, let’s look at some code example.
System.out.println("Area of shape");
class Circle extends Shape
System.out.println("Area of circle");
class Rectangle extends Shape
System.out.println("Area of rectangle");
public class Driver
public static void main(String args)
Shape s = new Shape();
s = new Circle();
s = new Rectangle();
In the above example, the call to area() method at line 30 is an example for static polymorphism. However at lines 31 and 33 the super class (Shape) reference s has been assigned objects of Circle and Rectangle respectively. Now the subsequent calls to area() method at lines 32 and 34 are bound at run-time which are an example for run-time polymorphism. Output of the above program is:
Area of shape
Area of circle
Area of rectangle
So, we can say that run-time polymorphism is possible only when there is inheritance and dynamic method dispatch.