C#: Extending the staff base class

This entry is part 51 of 71 in the series C#

To continue from the previous post, we will extend the base class Staff and add an engineer class.

We assume that engineer class would have a different hourly rate.

Extending the base class
using System;

namespace Company
{
    public class Staff
    {
        //protected declaration, only visible to derived class
        protected double rate;

        public Staff()
        {
            rate = 1;
        }

        public void salary()
        {
            double totalSalary = 30 * 8 * rate;

            Console.WriteLine(totalSalary);
        }
    }

    public class Engineer : Staff
    {
        public Engineer()
        {
            rate = 1.1;
        }
    }

    class Program
    {
        static void Main()
        {
            Staff staff = new Staff();
            staff.salary();

            Engineer engineer = new Engineer();
            engineer.salary();

            Console.ReadKey();
        }
    }
}

As you could see from line 22, class Engineer is based on class Staff.

public class Engineer : Staff

We have minimum code needed for class Engineer except a constructor that sets the rate to 1.1.

No variable declaration is needed in class Engineer as the rate variable is inherited from the base class.

The salary method is also inherited from the base class.

 

Series Navigation<< C#: Inheritance or specialization
C#: Modifying method behavior in derived class using new keyword >>

Leave a comment

Leave a Reply