What is Multi-Level Inheritance?
Multi-level inheritance is a type of inheritance where a class derives from another derived class, forming a multi-level hierarchy. This forms a parent-child-grandchild relationship.
Example Structure:
-
Class A: Base Class
-
Class B: Derived from Class A
-
Class C: Derived from Class B
Hierarchy:Class A → Class B → Class C
Benefits of Multi-Level Inheritance:
-
Promotes code reuse.
-
Establishes a clear hierarchy.
-
Allows for method overriding at multiple levels.
-
Enables the creation of more specific functionalities at each level.
Program Statement:
Mahesh is working on a software system for LotusJavaPrince
and wants to implement a simple multi-level inheritance structure to represent employees. The structure should include:
-
Employee (Base Class): Contains common employee attributes.
-
Manager (Intermediate Class): Inherits from Employee and adds specific attributes for a manager.
-
SoftwareEngineer (Derived Class): Inherits from Manager and adds specific attributes for a software engineer.
Program: Multi-Level Inheritance Implementation
// Employee.java class Employee { String name; int id; Employee(String name, int id) { this.name = name; this.id = id; } void displayDetails() { System.out.println("Employee Name: " + name); System.out.println("Employee ID: " + id); } } // Manager.java class Manager extends Employee { String department; Manager(String name, int id, String department) { super(name, id); this.department = department; } void displayManagerDetails() { displayDetails(); System.out.println("Department: " + department); } } // SoftwareEngineer.java class SoftwareEngineer extends Manager { String project; SoftwareEngineer(String name, int id, String department, String project) { super(name, id, department); this.project = project; } void displayEngineerDetails() { displayManagerDetails(); System.out.println("Project: " + project); } } // MainClass.java public class MainClass { public static void main(String[] args) { SoftwareEngineer se = new SoftwareEngineer("Mahesh", 101, "IT", "BankingApp"); System.out.println("Software Engineer Details:"); se.displayEngineerDetails(); } } /* Software Engineer Details: Employee Name: Mahesh Employee ID: 101 Department: IT Project: BankingApp */