Polymorphism
Students learn that different objects can use the same method name and each respond in their own way.
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."
-
1
One method name, many versions
Cat and Dog both
extends Animal, and each writes its ownspeak(). Re-writing a parent method in a child is called overriding. -
2
The magic: you don't need to check
Loop over a list of animals calling
animal.speak()— noif cat... if dog...needed. Each object automatically uses its own version. The right sound comes out by itself. -
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.
Call the same method on different objects.
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();
}
Program result
- Run your code to see output.
Type real JavaScript, then run it.
You called the same method on different objects and each object answered differently.
Open Polymorphism Builder