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
What Is It?

One command, many behaviors.

Polymorphism means different objects understand the same method name but perform it in their own way. Both pets receive speak(); the cat meows and the dog barks.

Metaphor

One remote button, different devices.

Press power on a television and it shows a picture. Press power on a fan and it spins. The command is the same, but each object knows its own response.

When Is It Used?

When a group shares an action.

Games use it for characters that all attack(), instruments that all play(), or pets that all speak(). New types can join without rewriting the loop.

Same JavaScript Command

The loop does not ask which pet it found.

class RoboCat extends RoboPet {
  speak() { return "meow"; }
}

class RoboDog extends RoboPet {
  speak() { return "bark"; }
}

let pets = [pixel, bolt];

for (let pet of pets) {
  pet.speak();
}
Repeated commandpet.speak()Each object chooses its own version.
Robo Pet Sound Lab

Watch the same command choose two behaviors.

pets[0]Pink robo cat named PixelPixel the RoboCat
Waiting for speak()
pets[1]Blue robo dog named BoltBolt the RoboDog
Waiting for speak()
Loop ready: 0 of 2 objects called

Press Run. JavaScript will send the exact same speak() message to both pets.