What is the difference between static and dynamic binding in Java?
sobes.tech AI
Answer from AI
Static (Compile-time) binding occurs at the compilation stage. The compiler determines the called method based on the reference type. It is used for private, static, final methods, and constructors because their implementation is known during compilation.
Dynamic (Runtime) binding occurs at the execution stage. The Java Virtual Machine (JVM) determines the called method based on the actual type of the object that the variable references. This is the main mechanism when working with polymorphism, where a subclass overrides a superclass method.
Example:
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
}
public class BindingExample {
public static void main(String[] args) {
Animal animal = new Dog(); // Static type Animal, dynamic type Dog
animal.makeSound(); // Dynamic binding - will call makeSound() from Dog
}
}
In this example, animal.makeSound() demonstrates dynamic binding. Although the variable animal has a static type of Animal, the actual object it references is an instance of Dog. The JVM determines this at runtime and calls the overridden makeSound() method from the Dog class.
Comparison:
| Characteristic | Static Binding | Dynamic Binding |
|---|---|---|
| Binding stage | Compilation | Runtime |
| Determined by | Reference type | Actual object type |
| For methods | private, static, final, constructors |
Virtual methods (regular instance methods) |
| Supports polymorphism | No | Yes (via method overriding) |
| Speed | Faster | Slower (small JVM overhead) |