Junior — Middle
How do static and dynamic method binding differ in Java and what are their features?
sobes.tech AI
Answer from AI
In Java, static and dynamic method binding differ in when the specific method implementation is chosen for invocation.
-
Static binding occurs at compile time. It includes calls to static methods, private methods, and final methods. The compiler knows which method to call and links the call to a specific implementation.
-
Dynamic binding occurs at runtime. It is characteristic of virtual methods (regular instance methods), which can be overridden in subclasses. The JVM determines at runtime which method to invoke based on the actual type of the object.
Example:
class Animal {
void sound() {
System.out.println("Some sound");
}
static void staticMethod() {
System.out.println("Static method in Animal");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
static void staticMethod() {
System.out.println("Static method in Dog");
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
a.sound(); // dynamic binding, calls Dog.sound()
a.staticMethod(); // static binding, calls Animal.staticMethod()
}
}
Ultimately, dynamic binding provides polymorphism, while static binding offers faster and more predictable behavior for methods that cannot be overridden.