OOP Studio Ages 9-15
Polymorphism
Students learn that different objects can use the same method name and each respond in their own way.
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.
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 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.
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 command
pet.speak()Each object chooses its own version.Watch the same command choose two behaviors.
pets[0]
Pixel the RoboCat
Pixel the RoboCatWaiting for speak()
pets[1]
Bolt the RoboDog
Bolt the RoboDogWaiting for speak()
Loop ready: 0 of 2 objects called
Press Run. JavaScript will send the exact same speak() message to both pets.
Polymorphism ran!
The loop called speak() twice. Each robo pet selected its own version automatically.