Inheritance
- Keshari Abeysinghe

- Mar 27, 2020
- 1 min read
Updated: Nov 30, 2020
Inheritance is a mechanism in which one class acquires the property of another class.For example, a child inherits the traits of his/her parents. With inheritance, we can reuse the fields and methods of the existing class. Hence, inheritance facilitates Reusability and is an important concept of OOPs.Inheritance represents the IS-A relationship which is also known as a parent-child relationship.The parent class is called a super class and the inherited class is called a subclass. The keyword extends is used by the sub class to inherit the features of super class.
Inheritance is important for Method Overriding (so runtime polymorphism can be achieved) and for Code Re-usability.
Following example shows the inheritance between two classes.
class Teacher{
float salary=40000;
}
class Tutor extends Teacher{
int bonus=10000;
public static void main(String args[]){
Tutor t=new Tutor();
System.out.println("Tutor salary is:"+t.salary);
System.out.println("Bonus of tutor is:"+t.bonus);
}
}
Expected Output
Tutor salary is:40000.0
Bonus of Tutor is:10000Types of inheritance
Single inheritance->In Single Inheritance one class extends another class (one class only).
Multiple inheritance->In Multiple Inheritance, one class extending more than one class. Java does not support multiple inheritance.
Multilevel inheritance->In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived class becomes the base class for the new class.
Hierarchical inheritance->In Hierarchical Inheritance, one class is inherited by many sub classes.
Multiple inheritance will discussed with abstraction of java in future articles.
Happy Coding!
Comments