Junior — Middle
What is the purpose of the concept of polymorphism in object-oriented programming?
sobes.tech AI
Answer from AI
Polymorphism in object-oriented programming allows objects of different classes to be treated through a common interface. This means that the same operation can behave differently depending on the type of object it is called on. Thanks to polymorphism, you can write more flexible and extensible code, where new classes are easily integrated without modifying existing code.
Example in Java:
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
System.out.println("Woof");
}
}
class Cat implements Animal {
public void sound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound(); // Outputs "Woof"
a = new Cat();
a.sound(); // Outputs "Meow"
}
}