This article describes Static and Dynamic Binding in Java.
- Actually, Static binding occurs when the type of an object is determined at compile-time on the basis of the declared type of a variable. Basically, we use Static binding for method overloading. In this case, the compiler determines which method to call on the basis of the type of arguments passed to the method.
- On the other hand, Dynamic binding occurs when the type of an object remains unknown till the runtime. Furthermore, the actual method call occurs on the basis of the actual type of the object. Therefore, we use Dynamic binding for method overriding. So, the method call occurs on the basis of actual type of object. Instead of the declared type.
Example of Static and Dynamic Binding in Java
class Animal {
public void makeSound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
Animal dog = new Dog();
animal.makeSound(); // Dynamic binding
dog.makeSound(); // Dynamic binding
Animal.makeSound(); // Static binding
}
}
In this example, Dynamic binding
refers to the fact that the method to be called is determined at runtime based on the actual object being referred to. When animal.makeSound()
is called, the Animal
class’s makeSound
method is called. When dog.makeSound()
is called, the Dog
class’s makeSound
method is called, even though the reference is of type Animal
.
On the other hand static binding, refers to the fact that the method call is determined at compile time. It is on the basis of the type of the reference. When Animal.makeSound()
is called, the Animal
class’s makeSound
method is called, because the reference is of type Animal
.