The mechanism of deriving a new class from an old one class is called inheritance. It provides flexibility to the child class to reuse the methods and variables of a parent class.
Parent Class (base class) – The class from which new one class is derived is called parent class. Parent class is also known as base class or super class.
Child Class (derived class) – The class which are derived from parent class is called child class. Also known as derived class, extended class or sub class.
Syntax:
class Fruits { //properties and methods... } class Vegetables extends Fruits { //properties and methods... } let fruits1 = new fruits(); let vegetables1 = new vegetables();
In the above example, there are two class. One is Fruits and other is Vegetables. In class Vegetables we have inherit the properties and methods of class Fruits using the ‘extends’ keyword. Now, when we create the object of class vegetables, we will have all the properties and methods of both class fruits and vegetables.
Let us understand with an example.
class employee { constructor(name) { this.name = name; console.log(`Constructor: Employee`); } detail() { console.log(`Employee Name: ${this.name}`) } } class manager extends employee { } let obj = new manager("Shivesh Singla"); // Constructor: Employee obj.detail(); // Employee Name: Shivesh Singla
If we have same method name in child class and parent class then child class method will be used over the parent class method.
If you want to use parent class method which is also available in child class then you have to use super.method_name().
class employee { constructor(name) { this.name = name; console.log(`Constructor: Employee`); } detail() { console.log(`Employee Name: ${this.name}`) } } class manager extends employee { detail() { super.detail(); console.log(`Manager Name: ${this.name}`); } } let obj = new manager("Shivesh Singla"); obj.detail(); #Output Constructor: Employee Employee Name: Shivesh Singla Manager Name: Shivesh Singla
Another Example:
class employee { constructor(name, dept, salary) { this.name = name; this.dept = dept; this.salary = salary; } detail() { document.writeln(`<h1>Employee Detail:</h1> Name : ${this.name} <br> Dept : ${this.dept} <br> Salary : ${this.salary} <br> `); } } class manager extends employee { detail() { let travel_allowance = 2000; let phone_allowance = 300; let total_salary = this.salary + travel_allowance + phone_allowance; document.writeln(`<h1>Manager Detail:</h1> Name : ${this.name} <br> Dept : ${this.dept} <br> Salary : ${total_salary} <br> `); } } let obj1 = new manager('Shivesh Singla', 'Technology', 90000); let obj2 = new employee('Kumar Deepak', 'Operation Management', 60000); obj1.detail(); obj2.detail(); #Output Manager Detail: Name : Shivesh Singla Dept : Technology Salary : 92300 Employee Detail: Name : Kumar Deepak Dept : Operation Management Salary : 60000