Static Binding in Java
Lets take one example to understand static binding in java.
class Demo { void show() { System.out.println("show"); } public static void main(String...s) { Demo d=new Demo(); d.show(); } }
Output
Show
Static Binding and Dynamic Binding in Java – Image Source |
Dynamic Binding in Java
1. When type of the object is determined by the compiler at run time, it is called as dynamic binding or late binding. We can also say that, in dynamic binding the method call is connected to the method body at run time.
2. The reference id of a derived class object is stored in reference variable of base class. We can only access the overridden methods, personal methods and variables of derived class can’t be accessed.
3. Dynamic binding occurs when there are overridden methods or method overriding.
Lets take one example to understand dynamic binding in java.
class Base { void show() { System.out.println("Base"); } } class Child extends Base { void show() { System.out.println("Child"); } public static void main(String...s) { Base b=new Child(); b.show(); } }
Output
Child
As you can see in the above example we are storing the reference id of Child class into the reference variable of Base class. When I have called show() method, the method of Child class is called and the output is “Child”. If Child class contains methods other then show() then they can’t be accessed using variable b. For accessing them we have to either type cast variable b or create another variable of Child class.
I hope that after reading this tutorial the concept of static binding and dynamic binding in java will be clear in your mind. I have also shared a video tutorial that will help you to understand these concepts easily. If you have any doubts and find anything incorrect in above tutorial then please mention it by commenting below.
This tutorial is really very helpful.