The source code to demonstrate the hierarchical inheritance in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//Program to demonstrate the hierarchical inheritance
//in C#.
using System;
class Human
{
public string name;
public int age;
public Human(int age, string name)
{
this.name = name;
this.age = age;
}
}
class Employee: Human
{
public int emp_id;
public int emp_salary;
public Employee(int id, int salary,string name,int age):base(age,name)
{
emp_id = id;
emp_salary = salary;
}
public void PrintEmployee()
{
Console.WriteLine("Emp ID: " + emp_id );
Console.WriteLine("Emp Name: " + name );
Console.WriteLine("Emp Salary: " + emp_salary );
Console.WriteLine("Emp Age: " + age );
Console.WriteLine("\n\n");
}
}
class Student : Human
{
public int student_id;
public int student_fees;
public Student(int id, int fees, string name, int age)
: base(age, name)
{
student_id = id;
student_fees = fees;
}
public void PrintStudent()
{
Console.WriteLine("Student ID: " + student_id );
Console.WriteLine("Student Name: " + name );
Console.WriteLine("Student Fees: " + student_fees);
Console.WriteLine("Student Age: " + age );
}
}
class Program
{
static void Main(string[] args)
{
Employee E = new Employee(101, 5000, "ALEX" , 20);
Student S = new Student (201, 2000, "Spensor" , 28);
E.PrintEmployee();
S.PrintStudent();
}
}
In the above program, we created three classes Human, Student, and Employee. Here we inherited Human class into both Student and Employee classes. Every class contains a constructor to initialize data members. Here we also created one more class Program that contains the Main() method. Then we created objects of Employee and Student class and print the information for student and employee using PrintStudent() and PrintEmployee() respectively.
Program:
The source code to demonstrate the hierarchical inheritance in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created three classes Human, Student, and Employee. Here we inherited Human class into both Student and Employee classes. Every class contains a constructor to initialize data members. Here we also created one more class Program that contains the Main() method. Then we created objects of Employee and Student class and print the information for student and employee using PrintStudent() and PrintEmployee() respectively.