JavaScript Class Inheritance
14 April 2025 | Category: JavaScript
Inheritance is a fundamental concept in object-oriented programming (OOP), and JavaScript supports it through classes and the extends
keyword.
It allows a child class to inherit properties and methods from a parent class, enabling code reuse and a cleaner structure.
đ Why Use Inheritance?
Imagine you have several objects that share some common behavior. Instead of repeating code, you define the shared logic in a base class, then extend it in other classes that add or override specific functionality.
đ§± Basic Example
đ§© Parent Class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
đ Child Class
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
â Usage
const dog = new Dog("Rex");
dog.speak(); // Output: Rex barks.
Dog
inherits fromAnimal
and overrides thespeak()
method.
đ§ Using super()
The super()
function is used to call the constructor or methods of the parent class.
class Vehicle {
constructor(type) {
this.type = type;
}
start() {
console.log(`Starting the ${this.type}`);
}
}
class Car extends Vehicle {
constructor(type, brand) {
super(type); // calls Vehicle's constructor
this.brand = brand;
}
start() {
super.start(); // calls Vehicle's start method
console.log(`${this.brand} is now running.`);
}
}
const myCar = new Car("Car", "Toyota");
myCar.start();
// Output:
// Starting the Car
// Toyota is now running.
đ Method Overriding
You can override a method from the parent class by redefining it in the child class. This allows for specific behavior.
class Bird extends Animal {
speak() {
console.log(`${this.name} sings.`);
}
}
const sparrow = new Bird("Sparrow");
sparrow.speak(); // Sparrow sings.
đ§Ș Inheriting Without Overriding
If a child class doesnât override a method, it will automatically use the parentâs version.
class Cat extends Animal {}
const kitty = new Cat("Milo");
kitty.speak(); // Milo makes a sound.
đ Inheritance Summary Table
Concept | Description |
---|---|
extends | Allows one class to inherit from another |
super() | Calls parent class constructor or method |
Method Overriding | Child class can define its own version of a method |
Code Reusability | Shared logic stays in the parent class |
đ Benefits of Class Inheritance
- Reduces code duplication
- Improves maintainability
- Makes your code more scalable
- Promotes cleaner architecture