Multilevel inheritance in Java language
In this tutorial, we will discuss the subject of Multilevel inheritance in Java language
Already, we have looked at multilevel inheritance in Inheritance in Java. Multilevel inheritance is one a concept in Java inheritance. A base class is inherited by a intermediate class and this derived class is inherited by a child class.
In the diagram below, class C inherits class B and class B inherits class A. This means class C is the child of class B and class B is the child to class A.
In the diagram above, we can clearly observe multilevel inheritance. We have three classes: principal, teacher and student. The principal is the base class, the teacher is the intermediate class and the student is the derived class. Class teacher extends from class principal and class student extends from class teacher. Now, we can access the data members and methods of the other two classes from the class student.
This is an example of multilevel inheritance. We have three classes in this example: student, teacher and principal. Teacher extends to students class and principal extends to teacher class. The principal class is able to use the methods of both student and teacher classes.
Example 1
Example 2
class students{ //class students is the parent class
int marks=78;
}class teacher extends students{ //class teacher is the inter mediate class
float salary=40000;
}
class principal extends teacher{ // class principal is the child class
float bonus=10000;
public static void main (String args[]){ //main method
principal p=new principal(); //create object
System.out.println(“teacher salary is:”+p.salary);
//access variable of teacher class from this class
System.out.println(“principal bonus is:”+p.bonus);
//access variable of this class
System.out.println(“principal marks is:”+p.marks);
//access variable of this class
}