HIERARCHICAL INHERITANCE

In Hierarchical inheritance one parent class will be inherited by many sub classes. As per the below example ClassA will be inherited by ClassB, ClassC and ClassDClassA will be acting as a parent class for ClassB, ClassC and ClassD.

Hierarchical_Inheritance_in_Java

Hierarchical Inheritance Example
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

1 comment:

  1. In Hierarchical inheritance one parent class will be inherited by many sub classes.perfect explanation about inheritance.its very useful.thanks for your valuable information.java training in chennai | list of java training institutes in chennai

    ReplyDelete