Dynamic binding is a technique used in Java to resolve method calls at runtime instead of compile-time. It is also known as late binding or dynamic method dispatch. Dynamic binding is an important aspect of runtime polymorphism in Java.
In Java, dynamic binding is achieved through method overriding. When a subclass overrides a method of its superclass, the method to be called is determined at runtime based on the actual type of the object that the reference variable refers to, rather than on the compile-time type of the reference variable.
Here’s an example to illustrate dynamic binding in Java:
public class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
public class TestDynamicBinding {
public static void main(String[] args) {
Animal animal = new Cat(); // create a new Cat object and assign it to the Animal reference variable
animal.makeSound(); // output: Meow
}
}
In this example, we have a superclass Animal
with a method makeSound()
, and a subclass Cat
that overrides the makeSound()
method. We then create a new Cat
object and assign it to an Animal
reference variable.
At runtime, the JVM determines that the actual type of the object that animal
refers to is Cat
, and thus calls the makeSound()
method in the Cat
class, resulting in the output “Meow”. This is an example of dynamic binding, where the method to be called is determined at runtime based on the actual type of the object, rather than on the compile-time type of the reference variable.
Dynamic binding is a powerful feature in Java that allows for flexible and extensible code. It enables polymorphism, which is one of the core principles of object-oriented programming.