In this java tutorial, we will understand the working of hierarchical inheritance in java with a program example. Hierarchical inheritance is again an extenstion to single inheritance as there are multiple single inheritance in this type. We have a complete explanation of Inheritance in Java so if you don’t know what Inheritance in Java is then check this article out.
In Hierarchical Inheritance, we have a single Super Class and a multiple Sub Classes which inherits the properties directly from this Super class.
Java Hierarchical Inheritance Program Example –
Class A { public void methodA() { System.out.println("Super class method"); } } Class B extends A { public void methodB() { System.out.println("Sub class Method B"); } } Class C extends A { public void methodC() { System.out.println("Sub class Method C"); } public static void main(String args[]) { A obj1 = new A(); B obj2 = new B(); C obj3 = new C(); obj1.methodA(); //calling super class method obj2.methodA(); //calling A method from subclass object obj3.methodA(); //calling A method from subclass object } }
Super class method
Super class method