Junior — Middle
Can you give an example of a situation where polymorphism is used in object-oriented programming?
sobes.tech AI
Answer from AI
Polymorphism in OOP allows objects of different classes to use the same interface but implement it differently. For example, we have a base class Animal with a method make_sound(). Derived classes Dog and Cat implement this method in their own way:
class Animal:
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "Woof"
class Cat(Animal):
def make_sound(self):
return "Meow"
animals = [Dog(), Cat()]
for animal in animals:
print(animal.make_sound())
Here, the same call to make_sound() for different objects results in different outputs — this is polymorphism.