Breaking News

Java Important concept - Static and Dynamic binding


Hi guys, Today I am going to discuss about a very important concept in JAVA ie. static and dynamic binding.




First of all Lets look at the definition of both these terms.

Static Binding:

When call to the function is resolved at compile time then method is getting statically bound. and its called static binding.

Dynamic Binding:

When call to the function is resolved at run time then method is getting dynamically bound. and its called dynamic binding. or when call to a function is resolved by looking at type of object rather than type of reference.

Lets see the concept with help of an example:

import java.util.*;

class P
{
//Start of Parent Class
void P1()
{
System.out.println("I am P1");
}
}
class C extends P
{
//Start of Child class that inherits Parent class
void P1()
{
System.out.println("I am Overrided P1");
}
}

class Binding
{
public static void main(String []args)
{
P obj = new P();
obj.P1();
}
}

Output: I am P1




Explaination: Here You can clearly see that we have Parent class reference and parent class object, and at compile time P1 is bound to be called and at runtime also same method is called, its called static binding.

Now lets take one more case.

P obj = new C();
obj.P1();

Output : I am Overrided P

Here we have child class object and parent class reference, Now at compile time P1 of parent class is bound to be called but at runtime JVM finds its updated definition in its child class so at runtime the decision changes and P1 from child class is called. This is called dynamic binding. ie. call to the function is resolved at runtime by looking at type of object rather than type of reference.

Why always a latest definition of method is called in java ?

Ans: In java in case of inheritence always the latest definition of a function in overrided class is called, This is because of virtual functions, If a function is declared virtual then latest definition of function is called. (Its a C++ concept), and in java all the functions are virtual by default hence latest definition is called.

Going more deeper this can be explained with the help of virtual table. We will explain that concept in next section.





No comments