C# - Employee Manager Example of Inheritance - Biz Tech

C# – Employee Manager Example of Inheritance

Listen
using System;

class Program
{
    static void Main(string[] args)
    {
        Employee employee1 = new Employee("John", "Smith", 50000);
        Console.WriteLine(employee1.GetInfo());

        Manager manager1 = new Manager("Jane", "Doe", 75000, "Sales");
        Console.WriteLine(manager1.GetInfo());
    }
}

class Employee
{
    protected string firstName;
    protected string lastName;
    protected double salary;

    public Employee(string firstName, string lastName, double salary)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.salary = salary;
    }

    public virtual string GetInfo()
    {
        return "Name: " + firstName + " " + lastName + ", Salary: $" + salary;
    }
}

class Manager : Employee
{
    private string department;

    public Manager(string firstName, string lastName, double salary, string department) : base(firstName, lastName, salary)
    {
        this.department = department;
    }

    public override string GetInfo()
    {
        return base.GetInfo() + ", Department: " + department;
    }
}
 

In this example, we have a base class Employee and a derived class Manager. The Employee class has protected fields firstName, lastName, and salary, and a method GetInfo() that returns a string with the employee’s name and salary. The Manager class inherits from Employee and adds a private field department, as well as an overridden GetInfo() method that includes the department in the output string.

In the Main() method, we create an Employee object and a Manager object, and call their respective GetInfo() methods. Because Manager inherits from Employee, we can treat the Manager object as an Employee object and call the GetInfo() method on it, which is overridden in the Manager class to include the department.

When we run the program, it outputs the following:

Name: John Smith, Salary: $50000
Name: Jane Doe, Salary: $75000, Department: Sales

This demonstrates inheritance, where a derived class inherits the fields and methods of a base class and can add its own fields and methods or override existing ones. This promotes code reuse and allows for more efficient and modular design.