Dynamic method dispatch in java

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.

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:

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 rectangle: 32
Area of square: 64
Area of triangle: 16

That’s all about Dynamic method dispatch in java.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.