Polymorphism in OOP — The Principle Explained

1 minute read

Polymorphism means “many forms.” In OOP, it means the same method name can behave differently depending on which object calls it.


The Analogy

The word “open” is polymorphic in everyday life:

  • Open a door → push/pull
  • Open a file → double-click
  • Open an app → tap the icon
  • Open a conversation → say hello

Same action name, different behavior depending on context.


Two Types in Java

1. Compile-Time Polymorphism (Method Overloading)

Same method name, different parameters — resolved at compile time.

class Calculator {
    int add(int a, int b) { return a + b; }
    double add(double a, double b) { return a + b; }
    int add(int a, int b, int c) { return a + b + c; }
}

2. Runtime Polymorphism (Method Overriding)

Same method signature, different implementation in child class — resolved at runtime.

class Animal {
    void sound() { System.out.println("..."); }
}

class Dog extends Animal {
    void sound() { System.out.println("Woof!"); }
}

class Cat extends Animal {
    void sound() { System.out.println("Meow!"); }
}

Animal a = new Dog();
a.sound();  // "Woof!" — decided at RUNTIME

Why Polymorphism Matters

// Without polymorphism — must check every type
void makeSound(Object animal) {
    if (animal instanceof Dog) ((Dog) animal).bark();
    else if (animal instanceof Cat) ((Cat) animal).meow();
    // what if we add Bird? Must modify this method!
}

// With polymorphism — clean and extensible
void makeSound(Animal animal) {
    animal.sound();  // works for ANY animal, now and future
}

Adding a new Bird class requires zero changes to makeSound().


Summary

  • Polymorphism = same interface, different behavior
  • Overloading (compile-time): same name, different parameters
  • Overriding (runtime): same signature, different implementation in child
  • Enables writing flexible, extensible code

→ Full implementation in the Polymorphism Deep Dive chapters.


What’s Next?

The final principle: Abstraction — hiding complexity to focus on essentials.

Updated: