Hierarchical Inheritance In Java with Example Program
Hierarchical Inheritance
Inheritance which contain only one parent class and multiple child class, and all child class directly extends the parent class this is called hierarchical inheritance
For example, consider A, B and C as three classes: A parent class,B and C are two child classes.Here B & C extends to A class,Similarly object should be created separately for B & C class.So B&A class property can be accessed using B class object. C&A class property can be accessed using C class
object.
Hierarchical Inheritance in java example program Program
class Parent { int age1=50; void display1() { System.out.println("This is parent class method disply1"); System.out.println("Parent class accessing through both obj1 and obj2"); System.out.println("____________________________________"); } } class Bchild extends Parent { int age2=40; void display2() { System.out.println("This is Bchild method and method2"); System.out.println("First child class of class parent"); System.out.println("____________________________________"); } } class Cchild extends Parent { int age3=30; void display3() { System.out.println("This is Cchild class and method disply3"); System.out.println("Second child class of class parent"); System.out.println("____________________________________"); } } class Mm { public static void main(String a[]) { Bchild obj1=new Bchild();//obj1 is Bchild class object name Cchild obj2=new Cchild();//obj2 is Cchild class object name System.out.println("____________________________________"); obj1.display1();//will print parent method obj1.display2();//will print Bchild method obj2.display3();//will print Cchild method obj2.display1();//will print parent method System.out.println("parent age variable :"+obj1.age1); System.out.println("Bchild age variable :"+obj1.age2); System.out.println("Cchild age variable :"+obj2.age3); System.out.println("parent age variable :"+obj2.age1); System.out.println(); } }
observe the program and its output carefully
Comments
Post a Comment