Junior — Middle
Can you give an example of using polymorphism in object-oriented programming?
sobes.tech AI
Answer from AI
Polymorphism in object-oriented programming allows objects of different classes to have the same interface but different implementations of methods.
Example in Python:
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
animals = [Dog(), Cat()]
for animal in animals:
print(animal.speak()) # Will output "Woof" and "Meow"
Here, the speak method is implemented differently in the Dog and Cat classes, but it is called in the same way, which is an expression of polymorphism.