Junior — Middle
Explain the concept of dynamic binding in object-oriented programming.
sobes.tech AI
Answer from AI
Dynamic binding in object-oriented programming is the process of determining at runtime which implementation of a method to invoke, rather than at compile time. This allows polymorphism, where the same method call can behave differently depending on the actual object type.
For example, if you have a base class Animal with a method makeSound(), and subclasses Dog and Cat override this method, then calling makeSound() through a reference to Animal will invoke the method of the actual subclass object.
class Animal {
void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
}
class Cat extends Animal {
void makeSound() {
System.out.println("Meow");
}
}
Animal a = new Dog();
a.makeSound(); // Will print "Bark" thanks to dynamic binding
Thus, dynamic binding provides flexibility and extensibility of code.