In Java Multilevel Inheritance sub class will be inheriting a parent class and as well as the sub class act as the parent class to other class. Lets now look into the below flow diagram, we can see ClassB inherits the property of ClassA and again ClassB act as a parent for ClassC. In Short ClassA parent for ClassB and ClassB parent for ClassC.
The ClassC inherits the members of ClassB directly as it is explicitly derived from it, whereas the members of ClassA are inherited indirectly into ClassC (via ClassB). So the ClassB acts as a direct superclass and ClassA acts as a indirect superclass for ClassC.
Example of Multilevel Inheritance
We have 4 class Person, Staff, TemporaryStaff and MultilevelInheritanceExample (Main class). Here Person class will be inherited by Staff class and Staff class will be again inherited by the TemporaryStaff class. TemporaryStaff class can access the members of both Staff class(directly) and Person class(indirectly).
package com.javainterviewpoint; class Person { private String name; Person(String s) { setName(s); } public void setName(String s) { name = s; } public String getName() { return name; } public void display() { System.out.println("Name of Person = " + name); } } class Staff extends Person { private int staffId; Staff(String name,int staffId) { super(name); setStaffId(staffId); } public int getStaffId() { return staffId; } public void setStaffId(int staffId) { this.staffId = staffId; } public void display() { super.display(); System.out.println("Staff Id is = " + staffId); } } class TemporaryStaff extends Staff { private int days; private int hoursWorked; TemporaryStaff(String sname,int id,int days,int hoursWorked) { super(sname,id); this.days = days; this.hoursWorked = hoursWorked; } public int Salary() { int salary = days * hoursWorked * 50; return salary; } public void display() { super.display(); System.out.println("No. of Days = " + days); System.out.println("No. of Hours Worked = " + hoursWorked); System.out.println("Total Salary = " + Salary()); } } public class MultilevelInheritanceExample { public static void main(String args[]) { TemporaryStaff ts = new TemporaryStaff("JavaInterviewPoint",999,10,8); ts.display(); } }
Output :
Name of Person = JavaInterviewPoint Staff Id is = 999 No. of Days = 10 No. of Hours Worked = 8 Total Salary = 4000
Leave a Reply