Inheritance
Students learn how one class can extend another class and add its own special behavior.
Inheritance
Inheritance is a family tree for classes. The parent class teaches the basics â every GameCharacter can introduce itself. A child class extends the parent: a Wizard gets everything a GameCharacter has, plus its own spell.
-
1
The parent teaches the basics
class GameCharacterhandles what EVERY character needs â a name andintroduce(). Write it once, up at the top of the family tree. -
2
extends= "is a kind of"class Wizard extends GameCharactermeans a Wizard is a GameCharacter. It inheritsintroduce()for free and adds its owncastSpell(). -
3
Try it
Add a
Knight extends GameCharacterwith aswingSword()method. Both children can introduce themselves â neither had to re-learn it.
Make a special kind of object.
class GameCharacter {
constructor(name) {
this.name = name;
}
introduce() {
say("I am " + this.name + ".");
}
}
class Wizard extends GameCharacter {
castSpell() {
say(this.name + " casts a sparkle spell!");
}
}
let hero = new Wizard("Nova");
hero.introduce();
hero.castSpell();
Program result
- Run your code to see output.
Type real JavaScript, then run it.
You made a new class that extends another class and adds a special method.
Open Inheritance Builder