DEV Community

Sreekar Reddy
Sreekar Reddy

Posted on β€’ Originally published at sreekarreddy.com

🎭 Polymorphism Explained Like You're 5

One interface, many implementations

Day 60 of 149

πŸ‘‰ Full deep-dive with code examples


The Universal Remote Analogy

One remote controls many devices:

  • Press "Play" β†’ TV plays video
  • Press "Play" β†’ Music player plays audio
  • Press "Play" β†’ Game console starts game

Same button, different behaviors!

The remote doesn't care WHAT device - just that it responds to "Play".


How Polymorphism Works

class Cat:
    def speak(self):
        return "Meow!"

class Dog:
    def speak(self):
        return "Woof!"

class Cow:
    def speak(self):
        return "Moo!"

# Same interface, different behavior!
animals = [Cat(), Dog(), Cow()]

for animal in animals:
    print(animal.speak())

# Output:
# Meow!
# Woof!
# Moo!
Enter fullscreen mode Exit fullscreen mode

We call .speak() without knowing the specific animal type!


Why It's Powerful

Without polymorphism:

if isinstance(animal, Cat):
    animal.meow()
elif isinstance(animal, Dog):
    animal.bark()
elif isinstance(animal, Cow):
    animal.moo()
# Ugly! And breaks when you add new animals
Enter fullscreen mode Exit fullscreen mode

With polymorphism:

animal.speak()  # Just works!
# Add new animal? Just implement speak()!
Enter fullscreen mode Exit fullscreen mode

The Real Power

Add new types without changing existing code!

class Robot:
    def speak(self):
        return "Beep boop!"

# Works immediately with all existing code!
Enter fullscreen mode Exit fullscreen mode

In One Sentence

Polymorphism lets different objects respond to the same method call in their own unique way.


πŸ”— Enjoying these? Follow for daily ELI5 explanations!

Making complex tech concepts simple, one day at a time.

Top comments (0)