Hierarchical Inheritance in C Sharp With Easy Example

Hierarchical Inheritance in C# example – When more than one classes inherit the same class is known as hierarchical inheritance.

Consider a Hierarchical Inheritance example,

A Teacher is expertise in the subjects C# 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 C# programming subject in computer department and physics and chemistry in science department.

Hierarchical Inheritance
//Parent Class
class Teacher
{
}
//child Classes/subclasses

class ComputerDepartment : Teacher
{
}

class ScienceDepartment : Teacher
{
}

Hierarchical inheritance in C# example – Code

In this C# 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() {
		Console.WriteLine("Java programming...");
	}

    public void physics()
    {
 
		Console.WriteLine("Physics...");
	}

    public void chemistry()
    {
 
		Console.WriteLine("Chemistry...");
 
	}
}
 
// Inherits feature of Teacher class
class ComputerDepartment : Teacher {
 
	public void learn() {
		Console.WriteLine("ComputerDepartment : Learn...");
	}
 
}
 
// Inherits feature of same Teacher class
class ScienceDepartment : Teacher {
 
	public void learn() {
		Console.WriteLine("\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…

Related Posts