top of page

Inheritance

  • Writer: Keshari Abeysinghe
    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:10000

Types of inheritance

  1. Single inheritance->In Single Inheritance one class extends another class (one class only).

  2. Multiple inheritance->In Multiple Inheritance, one class extending more than one class. Java does not support multiple inheritance.

  3. 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.

  4. 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!

Recent Posts

See All
Aggregation in java

In Java, aggregation represents HAS-A relationship, which means when a class contains reference of another class known to have...

 
 
 
Polymorphism

Polymorphism in Java occurs when there are one or more classes or objects related to each other by inheritance. In other words, it is the...

 
 
 
Abstraction in Java

Abstraction in any programming language works in many ways. It can be seen from creating subroutines to defining interfaces for making...

 
 
 

Comments


Subscribe Form

Thanks for submitting!

©2020 by Quick Code. Proudly created with Wix.com

bottom of page