java

Multilevel inheritance in Java language

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.

Multilevel inheritance

 

Explanation
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
}
Karmehavannan

Recent Posts

Multiply two numbers in Java using scanner| 5 different ways

Multiply two numbers in Java using scanner| 5 different ways In this article, we will…

5 months ago

5 different ways to Divide two numbers in Java using scanner

5 Different ways to Divide two numbers in Java using scanner In this article, we…

5 months ago

Learn 8 Ways to Subtract Two Numbers Using Methods in Java

Learn 8 Ways to Subtract Two Numbers Using Methods in Java In this article, we…

6 months ago

10 ways to subtract two numbers in Java

10 ways to subtract two numbers in Java In this article, we will discuss the…

6 months ago

Java Code Examples – Multiply Two Numbers in 5 Easy Ways

Java Code Examples – Multiply Two Numbers in 5 Easy Ways In this article, we…

6 months ago

How to Divide two numbers in Java| 5 different ways

How to Divide two numbers in Java| 5 different ways In this article, we will…

6 months ago

This website uses cookies.