Back to Inheritance Challenge
OOP Studio Ages 9-15

Polymorphism

Students learn that different objects can use the same method name and each respond in their own way.

15-20 min Ages 9-15 OOP JavaScript

Polymorphism

Same button, different sound. Every Animal has a speak() method — but the Cat answers "meow" and the Dog answers "woof." Calling the same method on different objects gives each one's own version. That's polymorphism: "many shapes."

speak() 😺 🐶 "meow" "woof"
  1. 1

    One method name, many versions

    Cat and Dog both extends Animal, and each writes its own speak(). Re-writing a parent method in a child is called overriding.

  2. 2

    The magic: you don't need to check

    Loop over a list of animals calling animal.speak() — no if cat... if dog... needed. Each object automatically uses its own version. The right sound comes out by itself.

  3. 3

    Try it

    Add a Duck class whose speak() says "quack," drop it in the list, and run the loop again. The loop didn't change — that's the superpower.

Code Editor

Call the same method on different objects.

Example code
class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    say(this.name + " makes a sound.");
  }
}

class Cat extends Animal {
  speak() {
    say(this.name + " says meow.");
  }
}

class Dog extends Animal {
  speak() {
    say(this.name + " says woof.");
  }
}

let animals = [new Cat("Pixel"), new Dog("Bolt")];

for (let animal of animals) {
  animal.speak();
}
Output

Program result

Robot ready to speak your strings

Type real JavaScript, then run it.