Signup/Sign In

Runtime Polymorphism or Dynamic method dispatch

Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at runtime. This is how java implements runtime polymorphism. When an overridden method is called by a reference, java determines which version of that method to execute based on the type of object it refer to. In simple words the type of object which it referred determines which version of overridden method will be called.

upcasting in java


Upcasting in Java

When Parent class reference variable refers to Child class object, it is known as Upcasting. In Java this can be done and is helpful in scenarios where multiple child classes extends one parent class. In those cases we can create a parent class reference and assign child class objects to it.

Let's take an example to understand it,

class Game
{
 	public void type()
 	{  
 		System.out.println("Indoor & outdoor"); 
 	}
}

Class Cricket extends Game
{
 	public void type()
 	{  
 		System.out.println("outdoor game"); 
	}

 	public static void main(String[] args)
 	{
   		Game gm = new Game();
   		Cricket ck = new Cricket();
   		gm.type();
   		ck.type();
   		gm = ck;	//gm refers to Cricket object
   		gm.type();	//calls Cricket's version of type
 	}
}

Indoor & outdoor Outdoor game Outdoor game

Notice the last output. This is because of the statement, gm = ck;. Now gm.type() will call the Cricket class version of type() method. Because here gm refers to the cricket object.


Q. Difference between Static binding and Dynamic binding in Java?

Static binding in Java occurs during compile time while dynamic binding occurs during runtime. Static binding uses type(Class) information for binding while dynamic binding uses instance of class(Object) to resolve calling of method at run-time. Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.

In simpler terms, Static binding means when the type of object which is invoking the method is determined at compile time by the compiler. While Dynamic binding means when the type of object which is invoking the method is determined at run time by the compiler.