Class inheritance in JavaScript

Level 4229 keystrokes

Dog extends Animal, inheriting its constructor and overriding speak, so new Dog("Max").speak() returns "Max barks" instead of "Max makes a sound".

JavaScript code

// Defines the base class Animal
1class Animal {
// The constructor runs on new and receives the name
2 constructor(name) {
// Stores the name on the new instance
3 this.name = name;
4 }
// The base version of speak, used when a subclass does not override it
5 speak() {
// Returns a generic message built with a template literal
6 return `${this.name} makes a sound`;
7 }
8}
// Dog inherits from Animal; with no constructor of its own, it uses Animal's
9class Dog extends Animal {
// Overrides speak: this version replaces Animal's for Dog instances
10 speak() {
// this.name was set by the inherited constructor
11 return `${this.name} barks`;
12 }
13}
// Creates a Dog; Animal's constructor sets name to "Max"
14const dog = new Dog("Max");
// Calls the overriding speak and prints Max barks
15console.log(dog.speak());

Output

Max barks
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • {× 7
  • }× 7
  • (× 6
  • )× 6
  • ;× 5
  • .× 5
  • `× 4
  • "× 2
  • =× 2
  • $× 2

More JavaScript examples at level 4

← JavaScript typing practice