Course contentsShow
← JavaScript
Lesson 769 of 2,72318. ClassesFree lesson

Class Inheritance with extends

How the extends keyword creates a child class that inherits from a parent class.

Class Inheritance with extends

You'll learn how to create a child class that inherits properties and methods from a parent class using the extends keyword.

The Core Idea

When you have one class that represents a more specific version of another class, you can use extends to create a parent-child relationship. The child class automatically gets all the methods and behavior from the parent class, without you having to rewrite them.

Think of it like family traits: a child inherits characteristics from their parent, but can also have their own unique features. In programming, this lets you build specialized classes without duplicating code.

How extends Works

The extends keyword appears in the class declaration:

class Animal {
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(`${this.name} makes a sound`);
  }
}

class Dog extends Animal {
  // Dog inherits everything from Animal
}

const myDog = new Dog('Buddy');
myDog.speak(); // "Buddy makes a sound" - method inherited from Animal!

The Dog class is now a child class (or subclass) of Animal, the parent class (or superclass). Even though Dog has no methods of its own, instances of Dog can use the speak() method because they inherit it from Animal.

The Inheritance Chain

Behind the scenes, extends sets up the prototype chain so that Dog.prototype points to Animal.prototype. This means property and method lookups on Dog instances will search Animal if needed.

Key Takeaway: The extends keyword creates a child class that automatically inherits all methods and properties from its parent class, enabling code reuse and class specialization.