In this post, we will about Dynamic method dispatch which is also referred as run time polymorphism.
Dynamic Method Dispatch
Dynamic method dispatch is a technique by which call to a overridden method is resolved at runtime, rather than compile time.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.Dynamic method dispatch is performed by JVM not compiler.
Dynamic method dispatch allows java to support overriding of methods and perform runtime polymorphism.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.
1 2 3 4 5 |
Base b=new Base(); Derived d=new Derived(); b=new Derived(); //Base class reference refer to derived class object that is upcasting |
When parent class reference variable refers to a child class object than its called upcasting and using this technique dynamic method dispatch perform.
We can not use derived class reference to refer to a base class object.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package org.arpit.java2blog; class Rectangle { int l=8,b=4; int area; public void area() { area=l*b; System.out.println("Area of rectangle: "+area); } } class Square extends Rectangle { public void area() //overridden method { area=l*l; System.out.println("Area of square: "+area); } } class Triangle extends Rectangle { public void area() //overridden method { area=(b*l)/2; System.out.println("Area of triangle: "+area); } } public class Calculation { public static void main(String args[]) { Rectangle r=new Rectangle(); r.area(); r=new Square(); //superclass reference referring to subclass Square object so,at run time it will call Square area() r.area(); r=new Triangle(); //superclass reference referring to subclass Triangle object so,at run time it will call triangle area() r.area(); } } |
When you run above program, you will get below output.
Output:-
Area of square: 64
Area of triangle: 16
That’s all about Dynamic method dispatch in java.