Sobes.tech
Junior — Middle

What are the differences between static and dynamic method binding in Java?

sobes.tech AI

Answer from AI

In Java, there is a distinction between static and dynamic binding of methods based on the time of determination of which method will be called:

  • Static binding occurs during compilation. It includes calls to static methods, private methods, and methods called through a reference to a specific type (for example, calls to final or private methods). The compiler knows exactly which method will be called.

  • Dynamic binding occurs at runtime. It applies to virtual methods (usually non-static, non-final, and non-private methods). The JVM determines which method is overridden in the class of the object that the reference points to, and calls that method.

Example:

class Animal {
    void sound() { System.out.println("Animal sound"); }
    static void staticSound() { System.out.println("Static animal sound"); }
}

class Dog extends Animal {
    @Override
    void sound() { System.out.println("Bark"); }
    static void staticSound() { System.out.println("Static bark"); }
}

Animal a = new Dog();
a.sound();        // Calls Dog.sound() — dynamic binding
Animal.staticSound(); // Calls Animal.staticSound() — static binding

Thus, dynamic binding provides polymorphism, allowing overridden methods in subclasses to be called, while static binding fixes the call at compile time.