Junior — Middle
Explain the concept of polymorphism by types in object-oriented programming.
sobes.tech AI
Answer from AI
Polymorphism by types (parametric polymorphism) in object-oriented programming is the ability of functions or methods to work with different data types without changing their code. This is achieved through type parameterization (generics) or inheritance.
For example, in Python, polymorphism manifests through duck typing: a function can accept objects of different classes if they support the required methods or properties.
Example:
class Cat:
def sound(self):
return "Meow"
class Dog:
def sound(self):
return "Woof"
def make_sound(animal):
print(animal.sound())
make_sound(Cat()) # Meow
make_sound(Dog()) # Woof
Here, the make_sound function works with any object that has a sound method, regardless of its specific class. This is an example of polymorphism by types.