Inheritance in Java

It is concept of Java where attributes and methods are inherited from super to sub-class.
Let us first clear about super class and sub- class:
Super class: The class which is being inherited.It is also referred as parent class.
Sub-class: The class which inherits the super class. it is also called as child class.
The keyword “extends” is used to inherit from a class.

Syntax:

public child class extends parent class
{
    //properties and methods
}

IS-A relationship is demonstrated by Inheritance which can be referred as parent-child relationship.

Types of Inheritance

We have following types of inheritance.

  • Single Inheritance
  • Multi-Level Inheritance
  • Hierarchical Inheritance
  • Multiple Inheritance
  • Hybrid Inheritance

Single Inheritance

In single inheritance, single child class inherits from single parent class.

Single Inheritance
class farmers
{
   String crops="Wheat";
    void grows();
    {
       System.out.println(“Farmers grows Wheat”);
    }
}
public class Animals extends farmers
{
    void eat();
    {
       System.out.println(“Animals eat Wheat”);
    }

public static void main (String args[])
{
    Animals obj=new Animals();
    System.out.println(obj.crops);
     obj.grows();
     obj.eat();
  }
}

Multi-Level Inheritance

Multilevel inheritance refers to the type of Inheritance where the child class which inherits from parent class is parent to other child class.

Multilevel Inheritance

Example:

Class farmers
{
   String crops="Wheat";
    void grows();
    {
       System.out.println(“Farmers grows Wheat”);
    }
}
Class Animals extends farmers
{
    void eat();
    {
       System.out.println(“Animals eat Wheat”);
    }
}
Class Cat extends Animals
{
    void drink();
    {
        System.out.println(“Cat drinks milk”);
    }    

public static void main (String args[])
   {
       Animals obj=new Animals();
       System.out.println(obj.crops);
         obj.grows();
         obj.eat();
   }
}

Hierarchical Inheritance

When more than one class inherits from a single parent class then it is called as hierarchical inheritance.

Hierarchical Inheritance

Example:

Class Farmers
{
    void grows();
}
Class Dog extends Farmers
{
    void eats();
}
Class Cat extends Farmers
{
    void drink();
}
public static void main(String args[])
  {
     Cat obj=new Cat();
     obj.grows();
     obj.eats();
     obj.drink();
  }

Multiple Inheritance

When single child  inherits from multiple parents, it is known as Multiple Inheritance.
But Multiple Inheritance doesn’t exist through class in Java,we will explain it later.

Hybrid Inheritance

When single child inheriting properties from multiple parents is being inherited by Multiple parents, it is Hybrid Inheritance and it is also not possible through class.

Leave a Reply