Inheritance in Java

Introduction 

 
This article discusses inheritance and aggregation with appropriate examples and their applications.

Inheritance

 
Basically Inheritance is the mechanism by which an object can acquire all the properties and behaviours of the parent object.

The concept behind Inheritance is that you create new classes that are built upon existing classes. So, when you Inherit from an existing class, you actually reuse (inherit) the methods and fields of the parent class to your new class with new situations.

Inheritance represents an "is-a" relationship.

Inheritance is used for:
  • Method overloading
  • Code reusability
Syntax for Inheritance
 
class Subclass -name extends Superclass-name
{    
   //methods and fields

The Subclass name is known as a new class that has been created and the Superclass name is known as the parent class.

Understanding the idea of inheritance

inheritance

In the preceding figure, Monitor is the sub-class and the student is the super-class and there is an "is-a" relationship, that is Monitor is a student.

Here is an example to clarify:  
  1. class Student      
  2. {      
  3.     String name="Rahul";      
  4. }    
  5.     
  6. class Monitor extends Student      
  7. {      
  8.     int rollno=1234567;      
  9.     public static void main(String args[])      
  10.     {      
  11.         Monitor m=new Monitor();      
  12.         System.out.println("class monitor is:"+m.name);      
  13.         System.out.println("roll no. is:"+m.rollno);      
  14.      }     
  15.   }    
  16. }    
Output: class monitor is:Rahul
roll no. is:1234567

Types of inheritance

Basically there are the following three types of inheritance:
  • Single
  • Multilevel
  • Hierarchical
Types of inheritance
Hierarchical
 
Hierarchical

Multiple inheritances are not possible in Java for classes but can be done via an interface.

Here in multiple inheritances, there is an ambiguity that form which parent class, class c should inherit the properties.

The following example will clarify that: 
  1. class Home  
  2. {  
  3.     void Message()  
  4.     {  
  5.          System.out.println("How are you...???");  
  6.     }  
  7. }  
  8.   
  9. class Room  
  10. {  
  11.     void Message  
  12.     {  
  13.        System.out.println("If fine then welcome...");  
  14.     }  
  15. }  
  16.   
  17. class House extends Home,Message  
  18. {  
  19.     //if possible  
  20.      public static void main(String args[])  
  21.      {  
  22.         House h=new House();  
  23.         h.Message();  
  24.         //now which Message() method would be involked..??  
  25.      }  
  26. }   

Summary

 
In the above article, we studied inheritance in java