Javascript Class Inheritance
Inheritance is a way to acquire properties of one class to other class. Inheritance are provide an ability to reuse features of existing class. That is most important feature of object oriented programming. In Javascript, extend keyword are used to inherit a class properties.
class Base{
//class logic here
}
//Inhert Base class
class Derived extends Base{
//class logic here
}
Base class is parent class and derived class is child class. let seen an simple example of inheritance.
class Animal {
constructor(mammal,carnivorous){
this.mammal=mammal;
this.carnivorous=carnivorous;
}
info(){
console.log("Mammal : ",this.mammal);
console.log("Carnivorous : ",this.carnivorous);
console.log("-----------------");
}
}
class Dog extends Animal{
constructor(){
//Execute Base class constructor
super("Yes","Yes");
}
about(){
console.log("Detail About Dog");
this.info(); //execute base class method
}
}
class Cow extends Animal{
constructor(){
//Execute Base class constructor
super("Yes","No");
}
about(){
console.log("Detail About Cow");
this.info(); //execute base class method
}
}
//make objects
let cow = new Cow();
let dog = new Dog();
//execute methods
cow.about();
dog.about();
Detail About Cow
Mammal : Yes
Carnivorous : No
-----------------
Detail About Dog
Mammal : Yes
Carnivorous : Yes
-----------------
Basic of Inheritance
Constructor Execution
When define Base class and Derived class class constructor and create derived class object in this situation there is compulsory to calling Base class constructor within the Derived class constructor using super()method.
class Software{
constructor(type,languge){
this.type=type;
this.languge=languge;
}
specification(){
console.log("Type : ",this.type);
console.log("Languge : ",this.languge);
}
}
class Operator extends Software{
constructor(type,languge,cost){
//Execute Software class constructor
super(type,languge);
this.cost=cost;
}
about(){
//Access Base class method
this.specification();
console.log("Cost : ",this.cost);
}
}
let videoGame = new Operator("Desktop","Java",1000);
videoGame.about();
Type : Desktop
Languge : Java
Cost : 1000

This super() method are accept the parameter list. When in Base class constructor are defined parameter values.
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment