Learn Hierarchical Inheritance in java with example – When more than one classes inherit the same class is known as hierarchical inheritance.
Prerequisite:
Consider a Hierarchical Inheritance example,
A Teacher is expertise in the subjects java programming, physics and chemistry. So, The two departments i.e. computer department and science department can use the same teacher for teaching. He can teach java programming subject in computer department and physics and chemistry in science department.
Hierarchical inheritance Example
In this java program, Computer department and Science department classes both are child classes of Teacher class (parent class)
/*
* Example of hierarchical inheritance in java
*
*/
//Base class
class Teacher {
public void programming() {
System.out.println("Java programming...");
}
void physics() {
System.out.println("Physics...");
}
void chemistry() {
System.out.println("Chemistry...");
}
}
// Inherits feature of Teacher class
class ComputerDepartment extends Teacher {
public void learn() {
System.out.println("ComputerDepartment : Learn...");
}
}
// Inherits feature of same Teacher class
class ScienceDepartment extends Teacher {
public void learn() {
System.out.println("\nScienceDepartment : Learn...");
}
}
/*
* Test hierarchical inheritance
*/
public class TestHierarchicalInheritance {
public static void main(String[] args) {
ComputerDepartment cd = new ComputerDepartment();
cd.learn();
cd.programming();
// Science department
ScienceDepartment sd = new ScienceDepartment();
sd.learn();
sd.physics();
sd.chemistry();
}
}
Output:
ComputerDepartment : Learn…
Java programming…
ScienceDepartment : Learn…
Physics…
Chemistry…