Understanding static binding and dynamic binding is crucial for mastering method calls and polymorphism in Object-Oriented Programming, especially in languages like Java.
📌 What is Binding?
Binding means connecting a method call to the actual method implementation that will be executed.
In other words:
When you call
obj.someMethod()
, how does the JVM know which version ofsomeMethod()
to run? That’s binding.
🪝 1️⃣ Static Binding (Early Binding)
What is Static Binding?
- The method call is resolved at compile time.
- Happens when the compiler knows exactly which method to call based on the reference type.
- Used for: ✅ Static methods
✅ Private methods
✅ Final methods
✅ Overloaded methods (same method name, different parameters)
class Animal {
static void staticMethod() {
System.out.println("Animal static method");
}
private void privateMethod() {
System.out.println("Animal private method");
}
void speak() { // non-overridden method
System.out.println("Animal speaking");
}
}
Static binding calls
Animal.staticMethod(); // Compiler knows this is Animal's static method
Animal animal = new Animal();
animal.speak(); // Compiler binds directly to Animal.speak() (no overriding involved)
✅ No runtime decision-making — the method is locked down at compile time.
🔗 2️⃣ Dynamic Binding (Late Binding)
What is Dynamic Binding?
- The method call is resolved at runtime.
- Happens when the method is overridden and the actual object type (not the reference type) determines which method to call.
- This is a core part of polymorphism.
Example
class Animal {
void speak() {
System.out.println("Animal speaking");
}
}
class Dog extends Animal {
@Override
void speak() {
System.out.println("Dog barking");
}
}
Dynamic binding call
Animal animal = new Dog(); // Reference type is Animal, object type is Dog
animal.speak(); // Dog's speak() is called at runtime
✅ The compiler doesn’t know for sure which version of speak()
to call — this is decided at runtime, based on the actual object type.
🔥 Key Differences
Aspect | Static Binding | Dynamic Binding |
---|---|---|
When bound | Compile time | Runtime |
Works with | Static, private, final, overloaded methods | Overridden methods (polymorphism) |
Performance | Slightly faster (direct call) | Slightly slower (needs runtime lookup) |
Example | staticMethod() , overloadedMethod(int) | @Override methods in subclass |
⚠️ Important Rule
Overridden methods = dynamic binding
Overloaded, static, final, private methods = static binding
🚀 Quick Recap
Binding | Example |
---|---|
Static Binding | animal.staticMethod() , overloadedMethod() |
Dynamic Binding | animal.speak() (if overridden in a subclass) |