In JavaScript, class inheritance allows a class to acquire properties and methods from another class. This promotes code reuse and logical hierarchy.

💡 What is Inheritance?
Inheritance lets a new class (called child or subclass) adopt the features of an existing class (called parent or superclass).
The keyword extends is used to create a subclass that inherits from a parent class.
| Parent Class | Child Class |
|---|---|
class Animal { ... } |
class Dog extends Animal { ... } |
When a child class extends a parent, it automatically gets all its methods and properties. The child can also add or override methods.
📌 Deep Dive: Simple Inheritance
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a noise.`;
}
}
class Dog extends Animal {
speak() {
return `${this.name} barks.`;
}
}
const dog = new Dog("Buddy");
console.log(dog.speak()); // Buddy barks.
In this example:
DoginheritsAnimal's constructor andspeakmethod.- The
Dogclass overridesspeakto provide its own behavior.
💡 Using super
Inside a subclass, super calls the parent class's constructor or methods.
📌 Deep Dive: Calling super
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a noise.`;
}
}
class Cat extends Animal {
constructor(name, color) {
super(name); // Calls Animal constructor
this.color = color;
}
speak() {
return super.speak() + ` It is a ${this.color} cat.`; // Calls Animal speak
}
}
const cat = new Cat("Whiskers", "black");
console.log(cat.speak()); // Whiskers makes a noise. It is a black cat.
⚠️ Important
In subclass constructors, super() must be called before using this. Omitting it will cause a ReferenceError.
extends| Feature | Description |
|---|---|
extends | Defines a subclass that inherits from a parent class. |
| Inheritance | Subclass gets parent's methods and properties automatically. |
| Overriding | Subclass can redefine parent's methods to change behavior. |
super() | Used in constructor to call parent class constructor. |
super.method() | Calls parent class method from subclass. |
💡 Why Use Inheritance?
Inheritance helps organize code by creating a clear relationship between general and specialized classes, avoiding repetition and enhancing maintainability.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What does the extends keyword do in a JavaScript class?
Question 2 of 2
What must you do before using this inside a subclass constructor?
Loading results...