CodingNic

Object-Oriented Programming

Polymorphism

Object-Oriented Programming 32 min read

Polymorphism

Polymorphism

Different classes can use the same method name in their own way.

This idea is called polymorphism.

The word means “many forms”.

What Is Polymorphism?

Polymorphism means one method name can behave differently depending on the object.

Why It Matters

It helps you:

  • write flexible code
  • reuse method names
  • work with different object types
  • keep programs clean

Real Example

A dog and a cat can both make a sound.

But the sound is different.

  • Dog → Woof
  • Cat → Meow

Both can use a method named sound().

Example

python
class Dog:
    def sound(self):
        print("Woof")

class Cat:
    def sound(self):
        print("Meow")

dog = Dog()
cat = Cat()

dog.sound()
cat.sound()

Output

text
Woof
Meow

Same method name, different behavior.

Use in a Loop

python
animals = [Dog(), Cat()]

for animal in animals:
    animal.sound()

Output

text
Woof
Meow

The loop does not need to know the exact class.

Another Example

python
class Car:
    def move(self):
        print("Driving")

class Plane:
    def move(self):
        print("Flying")

items = [Car(), Plane()]

for item in items:
    item.move()

Output

text
Driving
Flying

Polymorphism with Inheritance

Child classes can replace a parent method.

python
class Animal:
    def sound(self):
        print("Sound")

class Dog(Animal):
    def sound(self):
        print("Woof")

class Cat(Animal):
    def sound(self):
        print("Meow")

pets = [Dog(), Cat()]

for pet in pets:
    pet.sound()

Output

text
Woof
Meow

Why This Is Powerful

You can write one loop or function that works with many object types.

Code Along

Create classes:

  • Teacher
  • Student

Both should have method role() with different outputs.

Mini Challenge

Create classes:

  • CreditCard
  • Cash

Both should have method pay().

Outputs:

text
Paid by card
Paid by cash

Use a list and loop through both objects.

Real World Use Case

Apps use polymorphism for payments, notifications, vehicles, game actions, and user roles.

Quiz

  1. What is polymorphism?
  2. Can two classes use the same method name?
  3. Why is polymorphism useful?
  4. How does a loop use polymorphism?

Assignment

Create classes Bird and Fish with method move() and print both actions.

Summary

You learned that polymorphism lets different classes use the same method name with different behavior.