Lesson 34 +10 XP

Java Polymorphism

Java Polymorphism

Polymorphism means many forms. It lets different classes use the same method name but with their own behavior, through inheritance.

Example

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

class Pig extends Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

Each subclass overrides animalSound() with its own version.

Method overriding

When a subclass defines a method with the same name and signature as its parent, the child version runs instead.

Calling overridden methods

Animal myAnimal = new Animal();
Animal myPig = new Pig();
Animal myDog = new Dog();
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();

Even though all three are typed as Animal, each prints its own sound. The actual object decides which version runs.

Why polymorphism

  • Write code that works with the parent type.
  • Let subclasses supply their own behavior.
  • Make programs easy to extend with new classes.

TL;DR

  • Polymorphism lets subclasses override parent methods.
  • The actual object, not the variable type, picks the method.
  • Overriding is the mechanism behind polymorphism.