Java Dynamic Binding
Dynamic binding is a mechanism in Java that enables a program to call an overridden method from a subclass at runtime rather than compile time. It is an important concept in object-oriented programming that allows the selection of a method to execute at runtime.
Syntax
class Parent {
void method() {
System.out.println("Parent's method");
}
}
class Child extends Parent {
void method() {
System.out.println("Child's method");
}
}
public class Main {
public static void main(String[] args) {
Parent obj = new Child();
obj.method();
}
}
Example
class Animal {
void makeSound() {
System.out.println("Animal is making a sound.");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Dog is barking.");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
animal.makeSound();
}
}
Output
Dog is barking.
Explanation
In the example above, we have a method makeSound()
defined in the Animal
class. This method is overridden in the Dog
class.
The main method creates an object of type Dog
and assigns it to a reference of type Animal
. At runtime, the version of the makeSound()
method in the Dog
class is called, rather than the version in the Animal
class. This is an example of dynamic binding.
Use
Dynamic binding is useful in situations where a method may be overridden by subclasses. It allows the correct version of the method to be called at runtime, even if the reference to the object is of a different type. This enables polymorphism and makes the code more flexible.
Important Points
- Dynamic binding in Java allows the selection of a method to execute at runtime.
- The correct version of the method is selected based on the type of the object, even if the reference to the object is of a different class.
- Dynamic binding is an essential concept in object-oriented programming that enables polymorphism.
Summary
Dynamic binding is a critical concept in Java that enables a program to call an overridden method from a subclass at runtime. It is useful for situations where a method may be overridden by subclasses, and it allows the correct version of the method to be called at runtime, enabling polymorphism and making the code more flexible.