Inheritance

Introduction

In an inheritance, we create the class from the existing class. The existing class knows as the parent/superclass. The class that is derived is known as the subclass/child class. The subclass inherits are the properties and methods of the superclass. The subclass can also define its functions and class. We use the inheritance to reuse the code and override the methods. Method overriding is also known as runtime polymorphism. Hence, we can achieve Polymorphism in Java with the help of inheritance. The relationship between classes is a relation. extend is a keyword that is used to perform inheritance.

Types of inheritance

Single inheritance

Screenshot from 2022-04-05 23-25-52.png

When a class inherits another class, it is known as single inheritance.

Multilevel inheritance

Screenshot from 2022-04-05 23-32-37.png

In multilevel inheritance, a subclass extends from a super-class and then the same subclass acts as a super-class for another class.

Hierarchical level inheritance

Screenshot from 2022-04-05 23-28-15.png

In hierarchical inheritance, multiple sub-classes extend from a single super-class.

Hybrid Inheritance

Screenshot from 2022-04-05 23-37-00.png

Hybrid inheritance is a combination of two or more types of inheritance. Hybrid inheritance is only possible by the interface.

Multiple Inheritance

In multiple inheritance, a single subclass extends from multiple super-classes. Multiple inheritance is only possible by the interface.

Can we do multiple inheritance in Java?

Java does not support the multiple inheritances. One of the reasons is the ambiguity. However, we can achieve multiple inheritance using interfaces.

Example of ambiguity

Assume that we have three classes. Person, human, and student. Students extends the person and the human class. Student is the sub-class and the human and person are the super-classes. Now the issue here is if in person and human both have methods with the same names. Then student class call method that is present in both classes with the same names compiler cannot differentiate which class method is student class mentioned.