Junior — Middle
What role does polymorphism play in object-oriented programming?
sobes.tech AI
Answer from AI
Polymorphism in object-oriented programming allows objects of different classes to be processed through a single interface, while each object can implement behavior in its own way. This provides flexibility and extensibility of the code.
The role of polymorphism:
- Allows writing generic code that works with a base type, with specific behavior defined in subclasses.
- Simplifies support and extension of the system — new classes can be added without modifying existing code.
- Promotes the implementation of the open/closed principle.
Example in Java:
interface Animal {
void makeSound();
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Woof");
}
}
class Cat implements Animal {
public void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
animal.makeSound(); // Outputs "Woof"
animal = new Cat();
animal.makeSound(); // Outputs "Meow"
}
}
Here, the same call to makeSound() behaves differently depending on the actual type of the object.