Inheritance
It is a concept in which another Object is using some property and methods of an object. Unlike most OOP languages where classes inherit classes, JavaScript Object inherits Object other Objects can reuse, i.e. certain features (property and methods)of one object.
The JavaScript class also supports inheriting like other languages such as Java and C++. To inherit a class, you have to use the extends keyword.
class Vehicle {
constructor(make, model, color) {
this.make = make;
this.model = model;
this.color = color;
}
getName( ) {
return this.make + " " + this.model;
}
}
class Car extends Vehicle{
getName( ){
return this.make + " " + this.model +" in child class.";
}
}
let car = new Car("Honda", "Accord", "Purple");
car.getName( ) ; // "Honda Accord in child class."
In the above example, we define a Vehicle class with certain properties and methods. Then we inherit the Vehicle class in the Car class, use all the property and method of Vehicle class, and define certain property and methods for Car.
Method Overriding: It allows a method in a child class to have the same name and method signature as that of a parent class.
super keyword is used to refer to the immediate parent class instance variable.