Early Binding and Late Binding in Java

Introduction

Binding refers to the process of associating a method call with the method's actual code. In Java, binding can occur at different times: at compile-time (early binding) or at runtime (late binding). Understanding the distinction between early and late binding is crucial for grasping how Java handles method invocation and polymorphism.

Early Binding (Static Binding)

Definition: Early binding, also known as static binding, occurs when the method call is resolved at compile-time. This means that the method to be invoked is determined during the compilation process.

Key Characteristics:

Example:

class Animal {
    private void display() {
        System.out.println("Animal display");
    }

    static void staticMethod() {
        System.out.println("Static method in Animal");
    }
}

public class TestStaticBinding {
    public static void main(String[] args) {
        Animal a = new Animal();
        a.display(); // Early binding: private method
        Animal.staticMethod(); // Early binding: static method
    }
}

Late Binding (Dynamic Binding)

Definition: Late binding, also known as dynamic binding, occurs when the method call is resolved at runtime. The actual method to be called is determined based on the object's runtime type.

Key Characteristics:

Example: