Java Dynamic Binding Dynamic Polymorphism

Static binding and static polymorphism is achieved through method overloading. Now let us go for dynamic polymorphism. Observe the following code.

Program of Java Dynamic Binding Dynamic Polymorphism
class Bird
{
  public void eat()			// I
  {
    System.out.println("All birds eat");
  }
}
class Peacock extends Bird
{
  public void eat()			// II
  {
    System.out.println("Peacock eats grains");
  }
}
class Vulture extends Bird
{
  public void eat()			// III
  {
    System.out.println("Vulture eats flesh");
  }
}
class Crane extends Bird
{
  public void eat()			// IV
  {
    System.out.println("Crane eats fish");
  }
}
public class DynamicPolyDemo
{
  public static void main(String args[])
  {
    Bird b1 = new Bird();                       b1.eat();     // calls I
    Peacock p1 = new Peacock();   b1 = p1;	b1.eat();     // calls II
    Vulture v1 = new Vulture();   b1 = v1;	b1.eat();     // calls III
    Crane c1 = new Crane();       b1 = c1;	b1.eat();     // calls IV
 }
}


Java Dynamic Binding Dynamic Polymorphism
Output screen of Java Dynamic Binding Dynamic Polymorphism

In the above code, Bird is inherited by three classes – Peacock, Vulture and Crane. It is an example of hierarchical inheritance.

Java Dynamic Binding Dynamic Polymorphism

Subclasses Peacock, Vulture and Crane overrides the eat() method of Bird.

	
       b1 = p1;	
       b1.eat();     

In the above statement, subclass Peacock object p1 is assigned to super class Bird object b1. Earlier, in Object Casting, we know if a subclass object is assigned to a super class object, the super class object will call subclass overridden method. As per this rule, b1 will call p1 eat() method. Infact, the b1 contains the reference of p1.

       b1 = v1;	
       b1.eat();     

Now, the Bird object b1 is assigned with the subclass Vulture object v1. Now the earlier p1 reference is replaced by v1. Now b1 points to v1 location. Now b1 calls v1 eat method.

                         
       b1 = c1;	
       b1.eat();   

Again, the v1 reference in the super class object b1 is replaced by Crane object c1. Now, b1 calls Crane's eat() method.

Observe the code, the statement b1.eat() prints 4 different outputs by calling 4 different eat() methods. The same method when called different times giving different values is known a polymorphism ("poly" means many and "morphism" means forms).

Java Dynamic Binding

Which eat() method is to be called is decided at runtime because in every statement the address of the earlier subclass object is replaced. This address replacement happens at runtime (and not at compile time). Which overridden method is to be called is decided (or binded) dynamically at runtime. This feature is known as dynamic binding. Because polymorphism is achieved dynamically at runtime, this is known as dynamic polymorphism.

Dynamic binding is also called as dynamic method dispatch as which overridden method is to be dispatched for execution is known at runtime.

Rules followed to achieve dynamic polymorphism

1. There must be method overriding.
2. Subclass object must be assigned to a super class object.

The rule followed is "when a subclass object is assigned to a super class object, the super object will call subclass overridden method".

We know earlier, static polymorphism which is achieved through method overloading.

Dynamic polymorphism through Interfaces

The same Bird program, in the earlier example, can be modified to suit with interfaces. Now declare Bird as an interface. We know that reference variables can be created with abstract classes and interfaces (but not objects). Read the following program.

interface Bird
{
  public abstract void eat();		// I
}
class Peacock implements Bird
{
  public void eat()			// II
  {
    System.out.println("Peacock eats grains");
  }
}
class Vulture implements Bird
{
  public void eat()			// III
  {
    System.out.println("Vulture eats flesh");
  }
}
class Crane implements Bird
{
  public void eat()			// IV
  {
    System.out.println("Crane eats fish");
  }
}
public class DynamicPolyDemo
{
  public static void main(String args[])
  {
    Bird b1;		// reference variable of interface
    Peacock p1 = new Peacock();	b1 = p1;	b1.eat();     // calls II
    Vulture v1 = new Vulture();	b1 = v1;	b1.eat();     // calls III
    Crane c1 = new Crane();	b1 = c1; 	b1.eat();     // calls IV
  }
}

Java Dynamic Binding Dynamic Polymorphism

Here Bird is interface and not a concrete class (in the earlier program it is concrete class).

  
       Bird b1;

b1 is reference variable and not object.

       b1 = p1;		
       b1.eat();

Subclass Peacock object is assigned to the reference variable b1 of interface Bird. Here, super class is an interface and eat() is an abstract method. When a subclass object is assigned to a super class reference variable, the reference variable calls subclass overridden method. Now, b1 calls subclass Peacock's eat() method.

The addresses of subclass objects, p1, v1 and c1, in the super class reference variable b1 are replaced in every statement dynamically at runtime. Every time when b1.eat() method is called, it prints different outputs. This is known as polymorphism. Because polymorphism is achieved at runtime dynamically, this is known as dynamic polymorphism. Here, dynamic polymorphism is achieved through interfaces.

28 thoughts on “Java Dynamic Binding Dynamic Polymorphism”

  1. public class Snake
    {
    public void swim()
    {
    Console.WriteLine(“Swims with the whole body”);
    }
    }

    public class Duck : Snake
    {
    public void swim()
    {
    Console.WriteLine(“Swims with legs”);
    }
    }

    public class Fish : Duck
    {
    public void swim()
    {
    Console.WriteLine(“Swims with fins”);
    }
    }
    public class Animal:Fish
    {
    static void Main(string[] args)
    {
    Snake sn = new Fish ();
    sn.swim();
    }
    }

    The above call to sn.swim is not calling Fish’s swim() method but rather calling its own method (Snake’s swim)

  2. Suppose a program..

    class A{
    void msg(){
    sop(“hello A”);
    }
    }

    class B extends A{
    void msg(){
    sop(“hello B”);
    }
    }

    class C extends A{
    void msg(){
    sop(“hello C”);
    }
    }

    class dispatch{
    psvm(String a[]){
    {
    A a=new A();
    A b=new B();
    A c=new C();
    a.msg();
    b.msg();
    c.msg();
    }
    }

    now plz explain what is the advantage of using polymorphism..we can also make 3 refrence of type A, B and C..then wht is the point of making three refrence of only one type tht of Parent class type..wht is the advantage..plz explain me i m so confuse

  3. What is the use of a Java concept-“Super class variable can reference a sub class object” i. e Dynamic Method Dispatch? Even though by doing this the the SuperClass variable can only be used to access those parts of the object defined by the SuperClass but can’t access subclass members.Which can even be achieved by the subclass object.

      1. actually i didnt get this concept clearly , polymorphism is when we have same method name in same/different classes , do it depends upon by which object we are calling the function from main class ?

  4. Abhinav Joshi

    Sir I made a constructor of Bird class. Then after that I made an object of its subclass. The constructor of Bird class is getting called.

  5. If we call eat() with sub class objects p1,v1,c1 then which methods will be invoked?
    if we call p1.eat() then also it prints “peacock eats grains ” then why should we use object casting.Sir could you please explain?

  6. Hi, Mr.Nageshwara Rao
    I have a query regarding Derived Casting.
    Can u please explain me with a program that y do v get an Runtime Error called Class Cast Exception and what is the solution to be undertaken.

    Regards,
    Mona

  7. Can you pl explain what’s the significance of having dynamic polymorphism in Java? What is the exact real life usage for this feature? In this case any way we are creating subclass object & then assigning that to a superclass reference variable. Instead of calling the method through the reference variable of super class we can invoke the same using respective subclass variable itself. I am sure when this feature is there they would have thought for good real life fit for this.

    1. 1. With one class (super class) object, we can get the result required by the user.
      2. User may pass any object he likes.
      3. If you call subclass object, each subclass may have different methods.
      4. When you extend super class, the sub classes will have uniform methods.
      5. The same method of super class, the sub class may fill with its own code.

  8. how can reference variable of Runnable interface call getClass() of java.lang.Object though getclass Method is not present in Runnable interface?

  9. The rule followed is “when a subclass object is assigned to a super class object, the super object will call subclass overridden method”.

    Runnable r= new Thread();
    System.out.println(“the class name of r is “+r.getClass());
    could you explain how r is able to call getClass() as it is not in Runnable interface.

  10. sir,pls tell me example program for separate method overloading and method overriding by using constructor..

    1. First of all constructors cannot be overridden but can be overloaded. You wanted method overloading using constructors. Following is the program.

      public class Demo
      {
      public Demo()
      {
      display();
      display(10);
      display(10, 20);
      }
      public void display()
      {
      System.out.println(“Hello 1”);
      }
      public void display(int x)
      {
      System.out.println(x);
      }
      public void display(int x, int y)
      {
      System.out.println(x*y);
      }
      public static void main(String args[])
      {
      new Demo();
      }
      }

  11. Hi
    I have a query related to this post ….
    Though you are saying that
    “when a subclass object is assigned to a super class reference, the super reference will call subclass overridden method”
    but we can also call the toString() method of Object Class and other methods of it
    from the superClass/interface reference …
    Despite they are not been overridden…..

    So , How why it is happening ???

    Will you please explain me …

    Regards
    Gaurav Sharma

Leave a Comment

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