-
Notifications
You must be signed in to change notification settings - Fork 0
23 Inheritance
Biswajit Sundara edited this page Aug 18, 2023
·
1 revision
The ES6 class syntax also supports inheritance using the extends keyword
- When one class inherits the attributes and methods of another class that is called inheritance.
- The class whose properties and methods are inherited is known as the Parent class.
- The class that inherits the properties from the parent class is the Child class.
- To create a class inheritance, use
extendskeyword. - Always use
super()in the child class constructor
- Car is a super set, and Ford, Mercedes etc are children of the parent class. They use the basic features of Car in general and then have their brand specific features.
- Son inherits all the properties and mannerisms from a father. Father and Son can stay in the same address, son can inherit the assets however the age will not be same.
class Father{
constructor(){
console.log("Father is called..");
this.address = "10 Park Street";
this.assets = "$125000";
}
getaddress(){
console.log(`Address is ${this.address}`);
}
getassets(){
console.log(`Asset worth is ${this.assets}`);
}
}
class Son extends Father{
constructor(age){
super();
console.log("Son is called..");
this.age = age;
}
getage(){
console.log(`My age is ${this.age}`);
}
}
const ranveer = new Son(21);
ranveer.getaddress();
ranveer.getassets();
ranveer.getage();class Animal {
constructor(name, sound) {
this.name = name;
this.sound = sound;
}
makeSound() {
console.log(`${this.name} says ${this.sound}`);
}
}
class Dog extends Animal {
constructor(name) {
super(name, 'Woof');
}
}
const dog = new Dog('Rex');
dog.makeSound(); // Output: "Rex says Woof"