Lesson 65 +20 XP

Class Inheritance

Class Inheritance

Inheritance lets one class take properties and methods from another.

The extends keyword

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return this.name + " makes a sound";
  }
}

class Dog extends Animal {
  speak() {
    return this.name + " barks";
  }
}

Dog inherits everything from Animal, but can override methods.

Using the child class

const dog = new Dog("Rex");
dog.name;      // "Rex" (inherited)
dog.speak();   // "Rex barks" (overridden)

The super keyword

super calls the parent class's constructor or methods:

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

Why inheritance?

  • Reuse code from a base class.
  • Create specialized versions of a general class.
  • Build hierarchies like Animal -> Dog -> Puppy.

TL;DR

  • extends makes a class inherit from another.
  • Child classes get the parent's properties and methods.
  • super calls the parent's constructor.
  • Inheritance reuses and specializes code.