Index
Polymorphism
Polymorphism means “many forms”.
In programming, polymorphism allows objects of different classes to be treated the same way, even if they behave differently.
🔁 In simple words: One function, many behaviors, depending on the object calling it.
🔸 Example 1: Polymorphism with Functions and Classes
class Cat:
def sound(self):
print("Meow")
class Dog:
def sound(self):
print("Woof")
# Common interface
def make_sound(animal):
animal.sound()
# Different objects
c = Cat()
d = Dog()
make_sound(c) # Output: Meow
make_sound(d) # Output: Woof
✅ Explanation:
- Both
Cat
andDog
classes have asound()
method. - The
make_sound()
function callssound()
, but the actual output depends on the object passed. - This is polymorphism — the same function behaves differently for different object types.
🔸 Example 2: Polymorphism with Inheritance
class Vehicle:
def start(self):
print("Starting vehicle...")
class Car(Vehicle):
def start(self):
print("Starting car...")
class Bike(Vehicle):
def start(self):
print("Starting bike...")
# Polymorphism in action
for v in (Car(), Bike()):
v.start()
✅ Output:
Starting car...
Starting bike...
Even though Car
and Bike
are both types of Vehicle
, they have their own version of the start()
method.