Inheritance in Java with example programs

In Java, here classes can be reused in several ways, this is done by creating new classes, reusing the properties of the existing class. This mechanism of deriving a new class from an old one that is called Inheritance. The inheritance allows subclasses to inherit all the variables and methods of their parent classes. There are four types of inheritance are exists:

  • Single inheritance
  • Multiple inheritance
  • Hierarchical inheritance
  • Multi-level inheritance
  • Note: In Java, it doesn’t implement the Multiple Inheritance. single inheritance

    Single Inheritance :

    In this inheritance, having only one superclass.
    In Fig: class A serves as a base class for the derived class B.
    Program:

    class rectangle
    {
     int length;
     int breadth;
    rectangle(int p, int q)
    {
     length=p;
     breadth=q;
    }
    int area()
    {
     return(length*breadth);
    }
    }
    class cuboid extends rectangle
    {
     int height;
     cuboid(int p, int q, int r)
    {
     super(p,q)
     height=r;
    }
    int volume()
    {
     return(length*breadth*height);
    }
    }
    class test
    {
     public static void main(String args[])
    {
     cuboid c1=new cuboid(15,10,8);
     int area1=rect.area();
     int volume1=rect1.volume();
     System.out.println("The Area of Rectangle:"+area1);
     System.out.println("The Volume of Cuboid:"+volume1);
    }
    }
    

    Output:

    The Area of Rectangle: 150
    The Volume of Cuboid: 1200
    

    Hierarchical Inheritance :

    In this inheritance, having one superclass and many subclasses. It supports the hierarchical design of a program.

    hierarchical inheritance

    In fig: class A serves as the base class for the derived class B, class C, class D.

    Multi-level Inheritance :

    Java supports Multi-level inheritance concept and uses it extensively in building its class library. multilevel inheritanceIt allows us to build a chain of classes.
    Class A serves as a base class for the derived class B which in turn serves as a base class for the derived class C.