CodeBlanks Logo Icon CodeBlanks

extends and super

JavaScript course · Advanced · Lesson 10/100

Learn to subclass with extends and call the parent with super.

Subclassing with extends

To derive a class from another class you use the extends keyword. The derived class is a subclass; the one it derives from is the parent.

class Animal {
  constructor(name) { this.name = name; }
}
class Dog extends Animal {}

Dog inherits all members of Animal and can add its own.

Calling super

In a subclass constructor you must call the parent's constructor with super(...) before using this. This lets the parent do its setup first.

class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }
}

Here super(name) runs the parent's constructor; then this.breed can be added.

Exercise Dog subclass

The Animal class below is given. Declare a subclass Dog with extends. Its constructor takes a name parameter, calls super(name), and assigns "Woof" to this.sound.

Show example solution
Inside the constructor first call super(name), then this.sound = "Woof".
Example solution:
class Dog extends Animal {
  constructor(name) {
    super(name);
    this.sound = "Woof";
  }
}

Test yourself

  1. What must be called before `this` in a subclass constructor?

    constructor() { /* ... */ }
    • this()
    • new Animal()
    • super()
    • extends
    Show answer

    super() — Correct! super() runs the parent constructor.

  2. Extend the class

    class Dog ____ Animal {}
    Show answer
    class Dog extends Animal {}
  3. Match the concepts

    extends
    subclass declaration
    super()
    parent constructor call
    super.method()
    parent method call
    subclass
    derived class

All lessons in Advanced