Hierarchical Inheritance Example in C#

In this example, we will learn how to implement hierarchical inheritance using C# program?
Submitted by Nidhi, on August 20, 2020 [Last updated : March 21, 2023]

Here we will create a C# program to demonstrate the hierarchical inheritance. Here we will create Human, Student, and Employee classes to implement hierarchical inheritance.

C# program to demonstrate the example of hierarchical inheritance

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();
    }
}

Output

Emp ID:      101
Emp Name:    ALEX
Emp Salary:  5000
Emp Age:     20



Student ID:      201
Student Name:    Spensor
Student Fees:    2000
Student Age:     28
Press any key to continue . . .

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.

C# Basic Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.