Skip to content
Low Level Design Mastery Logo
LowLevelDesign Mastery

Polymorphism

One interface, multiple implementations.

Polymorphism is the ability of different classes to be treated as instances of the same class through a common interface. It allows methods to do different things based on the object they’re acting upon, even though they share the same name.

The word “polymorphism” comes from Greek meaning “many forms”. In programming, it means that objects of different types can be accessed through the same interface.

  1. Duck Typing - “If it walks like a duck and quacks like a duck, it’s a duck”
  2. Method Overriding - Subclasses override parent methods
  3. Operator Overloading - Same operator works differently for different types

When classes inherit from a common base class, they can be used interchangeably:

classDiagram
    class Vehicle {
        +brand: str
        +model: str
        +year: int
        +start()* str
        +get_info() str
    }
    
    class Car {
        +start() str
    }
    
    class Motorcycle {
        +start() str
    }
    
    class ElectricVehicle {
        +start() str
    }
    
    Vehicle <|-- Car
    Vehicle <|-- Motorcycle
    Vehicle <|-- ElectricVehicle
    
    note for Vehicle "Polymorphism:\nSame interface,\ndifferent implementations"

Using abstract classes ensures all implementations provide required methods:

The same operator can work differently for different types:

  1. Code Reusability - Write code once, use with multiple types
  2. Flexibility - Easy to add new types without changing existing code
  3. Maintainability - Changes to one type don’t affect others
  4. Simplicity - One interface for multiple implementations
  5. Extensibility - Easy to extend functionality

Polymorphism is about flexibility - writing code that works with multiple types without knowing the specific type at compile time. It’s one of the most powerful features of object-oriented programming.

💡 Time to Practice!

Now that you understand the concepts, put them into practice with our interactive playground. Build UML diagrams, write code, and get AI-powered feedback.

Browse All Problems