PRIYA KDynamic binding means: The method that gets executed is decided at runtime, based on the actual...
Dynamic binding means:
The method that gets executed is decided at runtime, based on the actual object.
It is also called:
Runtime binding
Late binding
This happens mainly with method overriding.
Example
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}
Output
Dog barks
Why?
Animal a = new Dog();
means:
reference type = Animal
object type = Dog
At compile time, Java sees Animal.
But at runtime, actual object is Dog, so Java calls:
Dog's sound()
This is dynamic binding.
Which method is called? → sound()
Which actual object exists? → Dog
Executes Dog’s overridden method
Example
Parent class = general remote
Child class = TV remote / AC remote
Pressing same button behaves differently depending on actual device.
Dynamic vs Static Binding
Static Binding Dynamic Binding
Decided at compile time Decided at runtime
Method overloading Method overriding
Faster Slightly slower
Early binding Late binding
Static Binding Example
class Test {
static void show() {
System.out.println("Hello");
}
}
Static methods are bound at compile time.
Dynamic Binding Example
Animal a = new Dog();
a.sound();
Bound at runtime.
Easy memory trick
Overriding + object created at runtime = dynamic binding