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
, andstatic
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
Feature | Static Binding | Dynamic Binding |
---|---|---|
Time of Binding | Compile time | Runtime |
Applies To | Static, final, private methods | Overridden methods |
Polymorphism Type | Compile-time (Overloading) | Runtime (Overriding) |
Performance | Slightly faster | Slightly slower (due to lookup) |