Polymorphism - Rybd04/2143-OOP GitHub Wiki
Definition
Polymorphism
Allows objects of different classes to be treated as objects of a common superclass, typically through method overriding or method overloading (depending on the language).
Explanation
Allows different classes to respond to the same method call in different ways
Basic Code Example
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Bark"
class Cat(Animal):
def speak(self):
return "Meow"
def make_animal_speak(animal):
print(animal.speak())
make_animal_speak(Dog()) # Output: Bark
make_animal_speak(Cat()) # Output: Meow
Here, the make_animal_speak() function works with any object of type Animal, but the actual method called (speak) depends on the object passed in. This is polymorphism in action.
Image
Additional Resources
https://www.geeksforgeeks.org/polymorphism-in-java/ https://www.techtarget.com/whatis/definition/polymorphism