Inheritance
Inheritance is one of the key concepts of OOP. It is the concept that classes can have child classes that inherit the properties and methods from the parent class. For example, if you needed all sorts of vehicle objects in your application, you could specify a class named Vehicle
in which you specify some shared properties and methods of vehicles. You would then go ahead and create the specific child classes based on this Vehicle
class, for example, boat
, car
, bicycle
, and motorcycle
.
This could be a very simple version of the Vehicle
class:
class Vehicle {
constructor(color, currentSpeed, maxSpeed) {
this.color = color;
this.currentSpeed = currentSpeed;
this.maxSpeed = maxSpeed;
}
move() {
console.log("moving at", this.currentSpeed);
}
accelerate(amount) {
this.currentSpeed += amount;
}
}
Here we have two methods in our Vehicle
class: move
and accelerate
. And this could be a Motorcyle
class inheriting from this class...