Hierarchical Inheritance: This type of Inheritance is a bit complex than the other two types of Inheritance.In this type of Inheritance one class is inherited by many sub classes.It can also be called as one-to-many relationship.
In hierarchical inheritance,the method of accessing methods of base class and its own class is also different,but that's not a big problem,its difficult for beginners,i too had spent a lot time on understanding this type of Inheritance,so I had decided to present the hierarchical inheritance in the most simple way,below is the diagram and the code for hierarchical inheritance.
WAP to implement Hierarchical Inheritance in Java:
class base{
void display1(){
System.out.println("This is base class method");
}
}
class derived1 extends base //Derived1 class inherits base class
{
void display2(){
System.out.println("This is derived1 class method");
}
}
class derived2 extends base //Derived2 class inherits base class
{
void display3(){
System.out.println("This is derived2 class method");
}
}
class Tasic
{
public static void main(String args[])
{
derived1 d1=new derived1(); //Derived1 class object declared
d1.display2(); //Calling its own member
d1.display1(); //Calling base class member
derived2 d2=new derived2(); //Derived1 class object declared
d2.display3(); //Calling its own member
d2.display1(); //Calling base class member
}
}
The output is:
In hierarchical inheritance,the method of accessing methods of base class and its own class is also different,but that's not a big problem,its difficult for beginners,i too had spent a lot time on understanding this type of Inheritance,so I had decided to present the hierarchical inheritance in the most simple way,below is the diagram and the code for hierarchical inheritance.
WAP to implement Hierarchical Inheritance in Java:
class base{
void display1(){
System.out.println("This is base class method");
}
}
class derived1 extends base //Derived1 class inherits base class
{
void display2(){
System.out.println("This is derived1 class method");
}
}
class derived2 extends base //Derived2 class inherits base class
{
void display3(){
System.out.println("This is derived2 class method");
}
}
class Tasic
{
public static void main(String args[])
{
derived1 d1=new derived1(); //Derived1 class object declared
d1.display2(); //Calling its own member
d1.display1(); //Calling base class member
derived2 d2=new derived2(); //Derived1 class object declared
d2.display3(); //Calling its own member
d2.display1(); //Calling base class member
}
}
The output is:
0 comments: