Thursday, July 22, 2021

What is Static and Dynamic binding in Java with Example

Static and dynamic binding in Java is two important concepts that Java programmer should be aware of. this is directly related to the execution of code. If you have more than one method of the same name (method overriding) or two variables of the same name in the same class hierarchy it gets tricky to find out which one is used during runtime as a result of their reference in code. This problem is resolved using static and dynamic binding in Java. For those who are not familiar with the binding operation, its process is used to a link which method or variable to be called as a result of their reference in code.


Most of the references are resolved during compile time but some references which depend upon Object and polymorphism in Java are resolved during runtime when the actual object is available. In this Java tutorial, we will see some examples of static and dynamic binding and the differences between static binding and dynamic binding in Java.


Difference between Static and Dynamic binding in Java:

The difference between static and dynamic binding is a popular Java programming interview question that tries to explore candidates' knowledge on having compiler and JVM finds which methods to call if there is more than one method of the same name as it's the case in method overloading and overriding. 

This is also the best way to understand what is static binding and what is dynamic binding in Java.

In the next section, we will differentiate between both of them.

And, If you are new to the Java world then I also recommend you go through these Java class on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.

Static Binding vs Dynamic binding Java

Here are a few important differences between static and dynamic binding in Java written in point format. knowledge of static and dynamic binding is required to understand Java code and find out any bugs and issues while running a Java program. It also helps in troubleshooting and debugging in Java.



1) Static binding in Java occurs during Compile time while Dynamic binding occurs during Runtime.

2) private, final and static methods and variables use static binding and are bonded by the compiler while virtual methods are bonded during runtime based upon runtime object.

3) Static binding uses Type(Class in Java)  information for binding while Dynamic binding uses Object to resolve to bind.

3) Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime. Here is an example that will help you to understand both static and dynamic binding in Java.

Static Binding Example in Java

Here is an example of static binding in java, which will clear things on how overloaded methods in java are bonded during compile time using Type information.

public class StaticBindingTest {
 
    public static void main(String args[])  {
       Collection c = new HashSet();
       StaticBindingTest et = new StaticBindingTest();
       et.sort(c);
     
    }
   
    //overloaded method takes Collection argument
    public Collection sort(Collection c){
        System.out.println("Inside Collection sort method");
        return c;
    }
 
   
   //another overloaded method which takes HashSet argument which is sub class
    public Collection sort(HashSet hs){
        System.out.println("Inside HashSet sort method");
        return hs;
    }
     
}

Output:
Inside Collection sort method

In the above example of static binding in Java, we have an overloaded sort() method, one of which accepts Collection and the other accept HashSet. we have called sort() method with HashSet as an object but referenced with type Collection and when we run method with the collection as argument type gets called because it was bonded on compile-time based on the type of variable (Static binding)  which was collection.

Example of Dynamic Binding in Java

In the last section, we have seen example of static binding which clears things that static binding occurs on compile-time, and Type information is used to resolve methods. In this section, we will see an example of dynamic binding in java which occurs during run time and instead of Type or Class information, Object is used to resolve method calls.

public class DynamicBindingTest {

    public static void main(String args[]) {
        Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car
        vehicle.start();       //Car's start called because start() is overridden method
    }
}

class Vehicle {

    public void start() {
        System.out.println("Inside start method of Vehicle");
    }
}

class Car extends Vehicle {

    @Override
    public void start() {
        System.out.println("Inside start method of Car");
    }
}

Output:
Inside start method of Car

In this example of Dynamic Binding, we have used the concept of method overriding. Car extends Vehicle and overrides its start() method and when we call start() method from a reference variable of type Vehicle, it doesn't call start() method from Vehicle class instead it calls start() method from Car subclass because object referenced by Vehicle type is a Car object. 

This resolution happens only at runtime because objects are only created during runtime and are called dynamic binding in Java. Dynamic binding is slower than static binding because it occurs in runtime and spends some time to find out the actual method to be called.

That's all on the difference between static and dynamic binding in java. The bottom line is static binding is a compile-time operation while the dynamic binding is a runtime. one uses Type and the other uses Object to bind. static, private, and final methods and variables are resolved using static binding which makes their execution fast because no time is wasted to find the correct method during runtime.

35 comments:

  1. I think main difference is as per name suggest static binding is static and dynamic binding is dynamic means more flexible. also isn't it dynamic binding also called late binding ? which implies it happen late during execution time.

    ReplyDelete
  2. Does both static and dynamic bonding related to polymorphism ? I guess no. because all final static and private methods and variable resolved during compile time no matter whether they are overloaded or overridden.

    ReplyDelete
  3. I was looking for difference between static vs dynamic binding when I found this tutorial. Now I know exactly what is static binding and what is dynamic binding in Java. very precise and simple example helps me to understand both static and dynamic binding in java. Thanks

    ReplyDelete
  4. Its as simple as this:
    static binding - compile time resolution (mainly overloaded method)
    dynamic binding - run time resolution (mainly overridden method)

    ReplyDelete
  5. @Swati
    Yes both overloading and overriding is form of polymorphism because they are basically same name but different functionality. But I agree private and static method are resolved during compile time and also referred as Static binding.

    ReplyDelete
  6. i think in static binding example output is
    Inside HashSet sort method
    as the following example
    class A
    {
    public void hello()
    {
    System.out.println("hello in A");
    }
    }
    class B extends A
    {
    public void hello()
    {
    System.out.println("hello in B");
    }
    }
    class C
    {
    public static void main(String... args)
    {
    A a = new B();
    a.hello();
    }
    }
    output is----
    hello in B

    ReplyDelete
  7. No Dear, You are taking an example of overridding(same parameter in method having same signature)

    ReplyDelete
  8. This is a very good tutorial. But if you accept advice, you repeat sentences a lot. Usually experienced programmers need to get in depth as fast as possible :)

    ReplyDelete
  9. Hello, this is a great post as other in this blog. However i see this line:

    "Overloaded methods are bonded using static binding while overridden methods are bonded during compile time"

    It shouldn't be "... overriden methods are bonded during runtime through dynamic binding" ?

    Regards,

    ReplyDelete
  10. @Rafael B.C., good pickup. Surprised to see that typo for so long. Yes, Overridden methods are bonded during runtime, as objects are only created at runtime. Thanks for pointing that out.

    ReplyDelete
  11. Its a very good explanation, thanks. Millions of sites in the WEB use words "static context" but nobody seems to understand what it means

    ReplyDelete
  12. This is an example of dynamic dispatch or polymorphism, not dynamic binding. All names are statically bound at compile time. If you chose a different name in Car for the start method (and kept the @Override annotation), the example wouldn't compile because the name is statically bound. A perfect example of Java being a statically bound language (and not having dynamic binding) is the necessity of the Visitor pattern.

    A better example of dynamic binding in Java is JavaBeans, because the name of the property has to be looked up at runtime and bound to the correct get/set method.

    ReplyDelete
  13. thanqu for give the simle example of static binding.

    ReplyDelete
  14. What is the difference between Static polymorphism and Dynamic polymorphism???

    ReplyDelete
  15. When overloading or Overridden not there in program then what will be the Static or Dynamic ?

    ReplyDelete
  16. ReferenceType object = new ObjectType();

    Polymorphism only work on overriding, because polymorphism works by checking on "object type" of the object (is-A term), unlike overloading because it works by checking on "reference type" of the object

    just my opinion

    ReplyDelete
  17. sorry guys, but i want to know that can we say this , overloading is compile time polymorhisim and overriding is run-time polymorphisim, but in the case of static methods in overriding we can call it again compile time polymorphisim. tht means in overriding thre can be compile time or runtime polymorphisim but in the case of overloading it can only be compile time polymorphisim..? just clear my concept if any one knows.

    ReplyDelete
  18. What type of binding is there in below case :
    class A{}
    class B extends A { public void method(){} }

    A obj = new B();
    obj.method(); // type of binding ??

    ReplyDelete
  19. I know this is the Inheritance concept, But can you please explain how it works? Bcoz here reference type is super class assigned by object of subclass. (In the dynamic binding example, mentioned that "......because object referenced by Vehicle type is a Car object") so in the below example also object referenced by 'A' type is a 'B' object, then it should executes method in B class but it didn't. Please explain.

    What type of binding is there in below case :
    class A{}
    class B extends A { public void method(){} }

    A obj = new B();
    obj.method(); // type of binding ??

    ReplyDelete
  20. @Prabhakar, in your case it's dynamic binding because method() is a virtual method i.e. not static, final or private, hence it's resolved at runtime when program will actually run using late binding.

    ReplyDelete
  21. How we can identify dynamic or static

    ReplyDelete
  22. which one used mostly in real time either static binding or dynamic binding?why?

    ReplyDelete
  23. What type of binding is there in below case :
    class A{}
    class B extends A { public void method(){} }

    A obj = new B();
    obj.method(); // type of binding ??

    Ans: It is Run-time binding no doubt, but above code will give Compile time error, cannot find the symbol

    because you are calling the non-overridden method of B class with the reference of class A. So, do remember one that you can only call the overridden methods using class A (Base class) reference and won't able to call non-overridden methods of class B(Derived class).

    ReplyDelete
  24. @Anonymous, you are right. The compile time error is because there is no such method in class A. if you want to call a method only defined in class B, you need to cast the object and store in a reference of class B.

    ReplyDelete
  25. public class CompileTimeQus {

    public static void main(String[] args) {

    new CompileTimeQus().test();

    }

    public void test() {

    Collection c = new HashSet();

    A obj1 = new B();
    obj1.show(c);
    obj1.show(new HashSet());

    B objb = new B();
    objb.show(c);
    objb.show(new HashSet());

    }



    private class A {


    public void show(Collection c) {
    System.out.println("This is show() in A Class with Collection args");
    }


    }

    private class B extends A {

    public void show(HashSet hashSet) {
    System.out.println("This is show() in B Class with HashSet args");
    }


    }
    }

    can you explain how static binding works here ?

    ReplyDelete
  26. Hi Everyone, I don't think, there is any existence for Static binding for Method Overloading, becuase compiler always using the "InvokeVirtual" Instruction for binding the Overloaded methods.
    below is the example of Method Overlaoding:
    import java.lang.*;
    public class A{

    public void m1(){
    System.out.println("Hi this is without parameterized");
    }

    public void m1(int i){
    System.out.println("hi this is from Parameterised"+i);
    }

    public void m1(String s1){

    System.out.println("this is from String"+s1);
    }

    public static void main(String args[]){
    A a = new A();
    a.m1();
    a.m2(10);
    a.m3("ABC");
    }

    }

    =======================================
    After compilation you can see the compiler's instructions which clearly shows it always bind these methods as Runtime.


    import java.lang.*;
    public class A{

    public void m1(){
    System.out.println("Hi this is without parameterized");
    }

    public void m1(int i){
    System.out.println("hi this is from Parameterised"+i);
    }

    public void m1(String s1){

    System.out.println("this is from String"+s1);
    }

    public static void main(String args[]){
    A a = new A();
    a.m1();
    a.m2(10);
    a.m3("ABC");
    }

    }



    ReplyDelete
  27. Please correct me if i am wrong somehow.

    ReplyDelete
  28. Sorry Guys this is my code both Source and Compiled
    import java.lang.*;
    class B extends A{
    public void m1()
    {
    System.out.println("this is Overridden Method");
    }

    }

    public class Test{
    public static void main(String args[]){
    A a = new B();
    a.m1();
    }

    }
    After Compilation Code:

    Compiled from "A.java"
    public class A {
    public A();
    Code:
    0: aload_0
    1: invokespecial #1 // Method java/lang/Object."":()V
    4: return

    public void m1();
    Code:
    0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
    3: ldc #3 // String Hi this is without parameterized
    5: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
    8: return

    public void m1(int);
    Code:
    0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
    3: new #5 // class java/lang/StringBuilder
    6: dup
    7: invokespecial #6 // Method java/lang/StringBuilder."":()V
    10: ldc #7 // String hi this is from Parameterised
    12: invokevirtual #8 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
    15: iload_1
    16: invokevirtual #9 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
    19: invokevirtual #10 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
    22: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
    25: return

    public void m1(java.lang.String);
    Code:
    0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
    3: new #5 // class java/lang/StringBuilder
    6: dup
    7: invokespecial #6 // Method java/lang/StringBuilder."":()V
    10: ldc #11 // String this is from String
    12: invokevirtual #8 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
    15: aload_1
    16: invokevirtual #8 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
    19: invokevirtual #10 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
    22: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
    25: return

    public static void main(java.lang.String[]);
    Code:
    0: new #12 // class A
    3: dup
    4: invokespecial #13 // Method "":()V
    7: astore_1
    8: aload_1
    9: invokevirtual #14 // Method m1:()V
    12: aload_1
    13: bipush 10
    15: invokevirtual #15 // Method m1:(I)V
    18: aload_1
    19: ldc #16 // String ABC
    21: invokevirtual #17 // Method m1:(Ljava/lang/String;)V
    24: return
    }

    ReplyDelete
  29. for More Details you can also follow the link mentioned below:
    http://www.artima.com/underthehood/invocationP.html

    ReplyDelete
  30. noted, meanwhile you can zoom in your browser e.g. chrome or Firefox. Thanks

    ReplyDelete
  31. what is compile time? and what actually happens when i type javac during the compilation process, if all the class loading and other dynamic linking and loading happens in the run time. Then what actaully happens during the compile time?

    ReplyDelete
  32. How are the methods in a class (non static, non final and non private) that are not overridden in child class resolved? Runtime or compiletime?

    ReplyDelete
  33. Hello Gaurav, static methods are resolved at compile time that's why they are called class method because class exists at compile time but object is only created at runtime.

    ReplyDelete