Author Profile Altaf Shaikh
Altaf Shaikh

BE Engg | Python Dev | Content Writer | Founder of TeachMeBro | Blockchain Dev | Django

Inheritance in OOPs

October 15th 2020   19

Inheritance in OOPs
Inheritance in OOPs

Inheritance:

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.

Inheritance example

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:

base class example 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:

child class example 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:

Driver class example code

 

Types of inheritance:

  1. Single Inheritance: In single inheritance, subclasses inherit the features of one superclass.

Single Inheritance example

 

 

 

 

 

 

Syntax:

Single Inheritance example code

  1. 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.

Multilevel Inheritance example

Syntax:

Multilevel Inheritance example code

  1. Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub class.

Hierarchical Inheritance  example

Syntax:

Hierarchical Inheritance example code

  1. 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. 

 

Multiple Inheritance example

Syntax: 

Multiple Inheritance example code

  1. Hybrid Inheritance (Not supported in Java, but is achievable through Interfaces) : Hybrid inheritance is a combination of multiple inheritance and multilevel inheritance.

Hybrid Inheritance example

Syntax:

Hybrid Inheritance example code