Inheritance in Java

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 that:

class Student

{

    String name="Rahul";

}

class Monitor extends Student

{

    int rollno=1234567;

    public static void main(String args[])

    {

        Monitor m=new Monitor();

        System.out.println("class monitor is:"+m.name);

        System.out.println("roll no. is:"+m.rollno);

     }

  }

} 

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

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

The following example will clarify that:

class Home

{

    void Message()

    {

         System.out.println("How are you...???");

    }

}

class Room

{

    void Message

    {

       System.out.println("If fine then welcome...");

    }

}

class House extends Home,Message

{
    //if possible

     public static void main(String args[])

     {

        House h=new House();

        h.Message();

        //now which Message() method would be involked..??

     }

}

Up Next
    Ebook Download
    View all
    Learn
    View all