Wednesday, March 8, 2017

Dynamic Method Dispatch

Tags

Dynamic Method Dispatch is an important feature of java in which the call to a overridden method is resolved at runtime i.e:runtime polymorphism.

In this case the Superclass reference object is assigned the subclass objects hence according to the object referenced the version of overridden method is called.

Following example will illustrate the concept:

Code::

import java.util.*;
class Figure
{
    double a,b;
    Figure(double c,double d)
    {
        a=c;
        b=d;
    }
    void area()
    {
        System.out.println("Area: 0");
    }
}
class Rectangle extends Figure
{
    Rectangle(double c,double d)
    {
        super(c,d);
    }
    void area()
    {
        System.out.println("Area of Rectangle:"+a*b+" square meters");
    }
}
class Triangle extends Figure
{
    Triangle(double c,double d)
    {
        super(c,d);
    }
    void area()
    {
        System.out.println("Area of Triangle:"+0.5*a*b+" square meters");
    }
}
class Circle extends Figure
{
    Circle(double c)
    {
        super(c,c);
    }
    void area()
    {
        System.out.println("Area of Circle:"+3.142*a*a+" square meters");
    }
}
class Square extends Figure
{
    Square(double c)
    {
        super(c,c);
    }
    void area()
    {
        System.out.println("Area of Square: "+a*b+" square meters");
    }
}
public class Area 
{
       public static void main(String[] nt)
       {
           Rectangle r=new Rectangle(5,4);
           Circle c=new Circle(10);
           Square s=new Square(5);
           Triangle t=new Triangle(4,5);
           Figure f;
           f=r;
           f.area();         //rectangle area
           f=c;
           f.area();          // circle area
           f=s;
           f.area();         //square area
           f=t;
           f.area();        //triangle area
       }
}

Output::