Junior — Middle
How is polymorphism implemented in object inheritance?
sobes.tech AI
Answer from AI
Polymorphism in object inheritance is implemented through the ability of objects of different classes to use the same interface or methods, while the behavior of these methods may differ.
In Python, this is achieved by overriding methods in derived classes. For example:
class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal):
def speak(self):
print("Woof")
class Cat(Animal):
def speak(self):
print("Meow")
animals = [Dog(), Cat(), Animal()]
for animal in animals:
animal.speak()
Here, the speak method is called for objects of different classes, and each object responds in its own way — this is polymorphism.