Junior — Middle
Can you explain the concept of polymorphism in object-oriented programming?
sobes.tech AI
Answer from AI
Polymorphism in object-oriented programming is the ability of objects of different classes to respond to the same messages (method calls) in different ways. This allows using a single interface to work with different types of objects.
Example in Java:
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal a1 = new Dog();
Animal a2 = new Cat();
a1.sound(); // Outputs: Bark
a2.sound(); // Outputs: Meow
}
}
Here, the sound() method is called on objects of type Animal, but the behavior depends on the specific subclass — this is polymorphism.