Thuta Learning
AdvancedProgrammingbeginner

Polymorphism

Relax. We'll talk through this in plain words — no textbook voice.

Polymorphism literally means "many forms." You use a parent type, but the method's actual behavior can differ depending on the real type of the object. In Java OOP, this shows up most often with method overriding.

java
class Animal {
  public void makeSound() {
    System.out.println("The animal makes a sound");
  }
}

class Dog extends Animal {
  public void makeSound() {
    System.out.println("Dog says: Woof!");
  }
}

class Cat extends Animal {
  public void makeSound() {
    System.out.println("Cat says: Meow!");
  }
}

public class Main {
  public static void main(String[] args) {
    Animal animal1 = new Dog();
    Animal animal2 = new Cat();

    animal1.makeSound();
    animal2.makeSound();
  }
}

The variable type is Animal, but the actual object is Dog and Cat. When you call the method, it runs the overridden version based on the object's actual type.

You should see
Dog says: Woof! Cat says: Meow!

Real-World Use

Polymorphism is incredibly useful for handling different payment gateways, notification channels, or export formats through a common interface/method.

Easy traps

  • Don't mix up overloading and overriding. Overloading is about different parameters; overriding is about a child class changing the behavior of a parent method.