Introduction to Inheritance

Inheritance is the principle that you can apply your knowledge of a general category to more specific objects. The classes you create in object-oriented programming languages can inherit data and methods from existing classes. When you create a class by making it inherit from another class, you are provided with data fi elds and methods automatically; you can reuse fields and methods that are already written and tested.

Let’s create an employee class:

class Employee
{
       private int empNum;
       private double empSal;

       public int EmpNum
      {
          get
          {
               return empNum;
          }
          set
          {
               empNum = value;
          }
     }
     public int EmpSal
     {
          get
          {
               return empSal;
          }
          set
          {
               empSal= value;
          }
     }
     public string GetGreeting()
     {
          string greeting = "Hello. I am employee #" + EmpNum;
          return greeting;
     }
}

After you create the Employee class, you can create specific Employee objects, as in the following:

Employee receptionist = new Employee();
Employee deliveryPerson = new Employee();

These Employee objects can eventually possess different numbers and salaries.

Suppose we hire a new type of Employee who earns a commission as well as a salary. We can create a new class with name for example CommissionEmployee and provide this class with three fields (empNum, empSal, commissionRate) and three properties and a method. However, this would duplicate all the work that we already did in class Employee. The wise and alternative way to do this is to create the class CommissionEmployee that inherits from class Employee. We can just add one field (commissionRate) and one property.

class CommissionEmployee : Employee
{
     private double commissionRate;

     public double CommissionRate
     {
          get
          {
               return commissionRate;
          }
          set
          {
               commissionRate= value;
          }
     }
}

When you use inheritance to create the new CommissionEmployee class, you have the following advantage:

1. You save time because you don’t have to recreate all the fields and properties from the Employee class.

2. You reduce the chance of errors because the class Employee has already been tested and used.

3. You make easier for anyone who has used the Employee class to understand the CommissionEmployee class.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s