Inheritance
The process of obtaining the data members and methods from one class to another class is known as inheritance. It is one of the fundamental features of object-oriented programming.
Important points
In the inheritance the class which is give data members and methods is known as base or super or parent class.
The class which is taking the data members and methods is known as sub or derived or child class
The data members and methods of a class are known as features.
The concept of inheritance is also known as re-usability or extendable classes or sub classing or derivation.
Why use Inheritance?
1)For Method Overriding (used for Runtime Polymorphism).
2)For code Re-usability
How to use inheritance in Java
To Achieve inheritance between classes, we should use extends keyword.
Note: Only non-static members of a class will be involved in Inheritance
Output
Child method Parent method
types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
NOTE: Multiple inheritance is not supported in java
Why multiple inheritance is not supported in Java
To remove ambiguity. To provide more maintainable and clear design.
Important Points:
All public variables of Super class will be inherited by subclass.
All default variables will be inherited by all subclasses in the same package only. Subclasses outside the package will not inherit any default member.
Private members cannot be inherited by subclass because they will not be visible to the subclass and hence the subclass can create the Method or property with the same name without any problem.
Protected variables will be inherited by all subclasses in the same package or outside package (Different from default).
Methods which are not inherited cannot be overridden. And hence overridden rules cannot be applied to those Methods. But Methods can still be defined in subclass though those Methods will not be the overridden Method. Instead it defines a new Method.
Static Methods or variables do not take part in inheritance.
Even though static methods or variables do not take part in inheritance and cannot be overridden they can be redefined in subclass. The redefinition is not called overridden but hidden.
Last updated