What is the difference between static binding and dynamic binding?

In Java, binding refers to the process of connecting a method call to the method body. The key difference between static binding and dynamic binding lies in when this connection is made—compile time vs runtime.

🔹 Static Binding (Early Binding)

  • When? Happens at compile time.
  • What? The method call is resolved by the compiler based on the reference type.
  • Applies to:
    • private, final, and static methods
    • Method overloading
  • Why? These methods cannot be overridden, so the compiler knows exactly which method to call.

✅ Example:

class Animal {
    static void sound() {
        System.out.println("Animal makes sound");
    }
}

class Dog extends Animal {
    static void sound() {
        System.out.println("Dog barks");
    }
}

public class Test {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound(); // Output: Animal makes sound
    }
}

Even though a refers to a Dog, the method is static, so the compiler binds it to Animal.sound().

🔸 Dynamic Binding (Late Binding)

  • When? Happens at runtime.
  • What? The method call is resolved based on the actual object, not the reference type.
  • Applies to:
    • Overridden methods (non-static, non-final)
  • Why? The JVM decides which method to call based on the object’s actual class.

✅ Example:

class Animal {
    void sound() {
        System.out.println("Animal makes sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

public class Test {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound(); // Output: Dog barks
    }
}

Here, the method is resolved at runtime based on the actual object (Dog), not the reference type (Animal).

🧠 Summary Table

FeatureStatic BindingDynamic Binding
Time of BindingCompile timeRuntime
Applies ToStatic, final, private methodsOverridden methods
Polymorphism TypeCompile-time (Overloading)Runtime (Overriding)
PerformanceSlightly fasterSlightly slower (due to lookup)

Leave a Reply

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