Inheritance is the property of inheriting the properties from one class to another class. It represents a parent-child relationship
The class that inherits the properties (child class) is called a subclass. A subclass can also have its methods and the private methods of the superclass cannot be inherited by the subclass
The class whose properties are inherited (parent class) is called superclass
> The main advantage of implementing inheritance is code reusability which means we can reuse the fields and methods of the existing class when we create a new class
> It can be used for method overloading which means calling a method in the child class that is already present in the parent class, in this case child class version of the method is executed
Syntax for inheritance
Where extends is a keyword
Single inheritance inherits the features of one superclass. In the image below, the class Student serves as a superclass for the sub-class Teacher.
Program
In the above use case, man is the superclass and employee is the subclass
In multilevel inheritance, a subclass can be inherited by another class. Consider the below diagram Teacher is a subclass that inherits the base class Student whereas Teacher is inherited by Parents but Parents cannot access the features of Student
Program
In hierarchical inheritance a base class can be extended by more than one subclass
Program
To reduce the complexity of the language, multiple inheritances are not supported by Java. For example, Teachers and Parent classes have methods with the same name and if the method is invoked in subclass Student then there will be a contradiction in invoking the method and a compile-time error will occur.