Inheritance
Inheritance
Inheritance is the mechanism by which one class acquires the properties and features of another class. The class that inherits the properties is called as a sub-class (child class) while the class from which the property is inherited is called as the super-class (parent class).
A child class inherits properties of parent class with the help of extends keyword.
Syntax:
Inheritance can be further divided into the following types:
- Single level
- Multi-level
- Hierarchical
- Multiple
- Hybrid
Multiple and hybrid inheritance is not directly supported in java, instead it is achieved through the use of interfaces in java.
i. Single Inheritance
When a single class inherits the attributes and methods of another class, it is known as single inheritance.
Example:
Output:
In this example, we see how class Gravitational can inherit the method of Its parent class (FundamentalForce). This is an perfect example of parent-child relationship.
ii. Multi-level Inheritance
When a class 3 inherits attributes and methods from class 2 which in turn inherits its attributes and methods from class 1, it is called a multi-level inheritance.
It forms a child-parent-grandparent (or a parent-child-grandchild) relationship. Meaning that child inherits from the parent while the parent inherits from the grandparent.
Example:
Output:
In this example, we see how class StrongNuclearForce inherits the method of NuclearForce which in turn inherits the method of FundamentalForce. This is a classic example of a child-parent-grandparent relationship.
iii. Hierarchical Inheritance
Hierarchical inheritance is when two or more classes inherit from a single class. This can be easily visualized as a parent with more than one child. Here each child can inherit the properties of a parent.
Example:
Output:
As we can see, both the children can access the method of the parent class.