Skip to content

Inheritance

In one line

Inheritance is a mechanism where a new class derives properties and methods from an existing class.

In simple words

Inheritance lets you create a new class that automatically gets all the properties and methods of an existing class. The new class (child/subclass) can then add its own features or override inherited ones.

For example, if you have a Vehicle class with speed and stop(), you can create a Car class that inherits from Vehicle and adds numberOfDoors. The Car automatically has speed and stop() from Vehicle, plus its own numberOfDoors.

Inheritance promotes code reuse — you write shared behavior once in the parent and all children inherit it. However, deep inheritance hierarchies can be hard to maintain. Modern code often prefers composition (building objects from smaller pieces) over deep inheritance.

Example

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

class Dog extends Animal {
  speak() { return `${this.name} barks.`; }
}

const dog = new Dog("Rex");
console.log(dog.speak()); // "Rex barks."

Dog inherits from Animal. It overrides the speak() method to provide dog-specific behavior while keeping the name property from Animal.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary