Source Code - Types of inheritance.
Person.java
// Parent class
class Person
{
String sID, sName, sEmail;
int iAge;
Person(String sID, String sName, String sEmail, int iAge)
{
this.sID = sID;
this.sName = sName;
this.sEmail = sEmail;
this.iAge = iAge;
}
void displayPersonInfo()
{
System.out.println("ID: " + sID + ", Name: " + sName + ", Email: " + sEmail + ", Age: " + iAge);
}
}
Teacher.java
// Single Inheritance: Teacher inherits directly from Person
class Teacher extends Person
{
String sDepartment;
Teacher(String sID, String sName, String sEmail, int iAge, String sDepartment)
{
super(sID, sName, sEmail, iAge);
this.sDepartment = sDepartment;
}
void displayTeacherInfo()
{
displayPersonInfo();
System.out.println("Department: " + sDepartment);
}
}
Student.java
// Hierarchical Inheritance: Student inherits from Person
class Student extends Person
{
String sCourse;
Student(String sID, String sName, String sEmail, int iAge, String sCourse)
{
super(sID, sName, sEmail, iAge);
this.sCourse = sCourse;
}
void displayStudentInfo()
{
displayPersonInfo();
System.out.println("Course: " + sCourse);
}
}
HostelStudent.java
// Multilevel Inheritance: Person → Student → HostelStudent
class HostelStudent extends Student
{
String sHostelName;
int iRoomNumber;
String sWardenName;
boolean bMessFacility;
HostelStudent(String sID, String sName, String sEmail, int iAge, String sCourse,
String sHostelName, int iRoomNumber, String sWardenName, boolean bMessFacility)
{
super(sID, sName, sEmail, iAge, sCourse);
this.sHostelName = sHostelName;
this.iRoomNumber = iRoomNumber;
this.sWardenName = sWardenName;
this.bMessFacility = bMessFacility;
}
void displayHostelStudentInfo()
{
displayStudentInfo();
System.out.println("Hostel Name: " + sHostelName);
System.out.println("Room Number: " + iRoomNumber);
System.out.println("Warden Name: " + sWardenName);
System.out.println("Mess Facility: " + (bMessFacility ? "Yes" : "No"));
}
}
MainClass.java
public class MainClass
{
public static void main(String[] args)
{
// Single Inheritance
Teacher objTeacher = new Teacher("T101", "Dr. Anand", "
[email protected]", 45, "Computer
Science");
// Hierarchical Inheritance
Student objStudent = new Student("S201", "Nivetha", "[email protected]", 19, "B.Sc. CT");
// Multilevel Inheritance
HostelStudent objHostelStudent = new HostelStudent ("S301", "Vasuki", "vasuki", 20,
"B.Sc. IT", "Annai Hostel", 212, "Mrs. Ragavi", true );
System.out.println("=== Teacher Details ===");
objTeacher.displayTeacherInfo();
System.out.println("\n=== Student Details ===");
objStudent.displayStudentInfo();
System.out.println("\n=== Hostel Student Details ===");
objHostelStudent.displayHostelStudentInfo();
}
}