Class Inheritance in JavaScript

Level 5332 keystrokes

This demonstrates class inheritance with extends and super, and method overriding.

JavaScript code

// Base class (parent class)
1class Animal {
// Constructor initializes instance properties
2 constructor(name) {
3 this.name = name;
4 }
5
// Method that can be overridden by subclasses
6 speak() {
7 console.log(`${this.name} makes a sound.`);
8 }
9}
10
// Derived class (child class) extends Animal
// It inherits all properties and methods from Animal
11class Dog extends Animal {
// Dog's constructor takes additional parameter
12 constructor(name, breed) {
// super() calls the parent constructor
// Must be called before using 'this'
13 super(name);
// Add Dog-specific property
14 this.breed = breed;
15 }
16
// Override the parent's speak method
// This replaces Animal's speak for Dog instances
17 speak() {
18 console.log(`${this.name} barks!`);
19 }
20}
21
// Create a Dog instance
22const dog = new Dog("Buddy", "Golden");
// Calls Dog's overridden speak method
23dog.speak();
// Access Dog-specific property
24console.log(dog.breed);

Output

Buddy barks!
Golden
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.

  • .× 10
  • (× 10
  • )× 10
  • ;× 8
  • {× 8
  • }× 8
  • "× 4
  • `× 4
  • =× 3
  • ,× 2

More JavaScript examples at level 5

← JavaScript typing practice