Inheritance is an aspect of OOPs languages, which provides the ability of a program to create a new class from an existing class. It is a mechanism which acquires the properties and behaviors of a class from another class. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived/child/subclass. In child class, we can override or modify the behaviors of its parent class.
We can declare a class inheritance as below.
Why use inheritance?
As displayed in the above figure, Audi is the subclass and Car is the superclass. The relationship between the two classes is Audi IS-A Car. It means that Audi is a type of Car.
In the above example, the Audi class extends the Car class by using the extends keyword. It means the Audi class can include all the members of the Car class. The constructor of the Audi class initializes its own members as well as the parent class's properties by using a special keyword 'super.' The super keyword is used to call the parent constructor and its values.
Types of Inheritance
We can classify the inheritance into the five types. These are:
Note: TypeScript supports only single and multilevel inheritance. It doesn't support multiple, hierarchical, and hybrid inheritance.
Single inheritance can inherit properties and behavior from at most one parent class. It allows a derived/subclass to inherit the properties and behavior of a base class that enable the code reusability as well as we can add new features to the existing code. The single inheritance makes the code less repetitive.
When a derived class is derived from another derived class, then this type of inheritance is known as multilevel inheritance. Thus, a multilevel inheritance has more than one parent class. It is similar to the relation between Grandfather, Father, and Child.
When an object or class inherits the characteristics and features form more than one parent class, then this type of inheritance is known as multiple inheritance. Thus, a multiple inheritance acquires the properties from more than one parent class. TypeScript does not support multiple inheritance.
When more than one subclass is inherited from a single base class, then this type of inheritance is known as hierarchical inheritance. Here, all features which are common in sub-classes are included in the base class. TypeScript does not support hierarchical inheritance.
When a class inherits the characteristics and features from more than one form of inheritance, then this type of inheritance is known as Hybrid inheritance. In other words, it is a combination of multilevel and multiple inheritance. We can implement it by combining more than one type of inheritance. TypeScript does not support hybrid inheritance.