Hierarchical Inheritance in Java with Example

In this inheritance multiple classes inherits from a single class i.e there is one super class and multiple sub classes. As we can see from the below diagram when a same class is having more than one sub class (or) more than one sub class has the same parent is called as Hierarchical Inheritance.

Hierarchical_Inheritance_in_Java

Here ClassA acts as the parent for sub classes ClassB, ClassC and ClassD. Lets take a look into the below code.

public class ClassA 
{
    public void dispA()
    {
        System.out.println("disp() method of ClassA");
    }
}
public class ClassB extends ClassA 
{
    public void dispB()
    {
        System.out.println("disp() method of ClassB");
    }
}
public class ClassC extends ClassA
{
    public void dispC()
    {
        System.out.println("disp() method of ClassC");
    }
}
public class ClassD extends ClassA
{
    public void dispD()
    {
        System.out.println("disp() method of ClassD");
    }
}
public class HierarchicalInheritanceTest 
{
    public static void main(String args[])
    {
        //Assigning ClassB object to ClassB reference
        ClassB b = new ClassB();
        //call dispB() method of ClassB
        b.dispB();
        //call dispA() method of ClassA
        b.dispA();
        
        
        //Assigning ClassC object to ClassC reference
        ClassC c = new ClassC();
        //call dispC() method of ClassC
        c.dispC();
        //call dispA() method of ClassA
        c.dispA();
        
        //Assigning ClassD object to ClassD reference
        ClassD d = new ClassD();
        //call dispD() method of ClassD
        d.dispD();
        //call dispA() method of ClassA
        d.dispA();
    }
}

Output :

disp() method of ClassB
disp() method of ClassA
disp() method of ClassC
disp() method of ClassA
disp() method of ClassD
disp() method of ClassA

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *