Inheritance in JavaScript
In JavaScript, inheritance means that one class (child) can use the properties and methods of another class (parent).It’s a way to reuse code and create a logical relationship between objects.
We use the keyword extends in classes and super() to call the parent’s constructor.
Example of Inheritance
class Vehicle {
move() {
console.log("This vehicle is moving...");
}
stop() {
console.log("This vehicle has stopped.");
}
}
// Child class inheriting Vehicle
class Car extends Vehicle {
honk() {
console.log("Car says: Beep Beep!");
}
}
// Using it
let myCar = new Car();
myCar.move(); // from Vehicle
myCar.honk(); // from Car
myCar.stop(); // from Vehicle
Explanation:-
Parent Class (Vehicle) → Defines general behaviors (move() and stop()) common to all vehicles.
Child Class (Car) → Uses the extends keyword to inherit all properties and methods from Vehicle.
Additional Functionality → Car adds its own unique method honk(), while still having access to Vehicle’s methods.
Object Creation → let myCar = new Car(); creates an object of Car which can use both inherited methods (move, stop) and its own method (honk).
Reusability & Extensibility → Inheritance allows avoiding code duplication, so you can add more specific vehicle types (like Bike, Bus) that automatically get move() and stop() without rewriting them.