Inheritance in OOPs
October 15th 2020 20
In OOP, computer programs are designed in such a way where everything is an object that interacts with one another. Inheritance is one such concept where the properties of one class can be inherited by the other. It helps to reuse the code and establish a relationship between different classes.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Base Class: The class whose features are inherited is known as base class(or a super class or a parent class).
Let below snippet, be considered as base class of our code:
Child Class: The class that inherits the other class is known as child class(or a derived class, extended class, or sub class). The subclass can add its own fields and methods in addition to the superclass fields and methods. The keyword used for inheritance is extends.
Let below snippet, be considered as child class of our code:
# super keyword : Reference variable which is used to refer to an immediate parent class object. Whenever you create an instance of a subclass, an instance of the parent class is created implicitly which is referred to by a super reference variable.
Driver class which lets us see the output of our code:
Types of inheritance:
- Single Inheritance: In single inheritance, subclasses inherit the features of one superclass.
- Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class.
- Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub class.
- Multiple Inheritance (Not supported in Java, but is achievable through Interfaces) : In Multiple inheritance ,one class can have more than one superclass and inherit features from all parent classes.
- Hybrid Inheritance (Not supported in Java, but is achievable through Interfaces) : Hybrid inheritance is a combination of multiple inheritance and multilevel inheritance.