Runtime Polymorphism

One of the frequently seen situations from a technical standpoint in a large scale of Business Layer objects is, invoking methods from different objects when they contain same method name. Today, am going to make it simple to give an example for Runtime Polymorphism. Leave your comments if am mistaken

At this stage, I don’t think to mention about "Polymorphism", as hope that you are aware of how polymorphic behavior can be fused using C#. If you want a start up, in simple words, implementation of one Method with many definitions, as mentioned below.

class Employee
{
/// <summary>
/// Invoked for the Regular salaried employes
/// </summary>
/// <param name="intEmpId">Employee ID</param>
/// <param name="intAbscentDays">Number of days</param>
/// <returns></returns>

public long CalculateSal(int intEmpId, int intAbscentDays)
{
return (GetEmpSal(intEmpId) * (GetWorkingDays(DateTime.Now.Month) - intAbscentDays));
}

/// <summary>

/// Invoked for the employees, who work as Daily wage
/// </summary>
/// <param name="lSalPerDay">Salary per day</param>
/// <param name="intDays">For number of days</param>
/// <returns></returns>
public long CalculateSal(long lSalPerDay, int intDays)
{
return lSalPerDay * intDays;
}
}

A simple way of invoking is as mentioned below.

Employee eTe = new Employee();

long lSal = eTe.CalculateSal(124, 2);
long lSal = eTe.CalculateSal(678.35, 18);

So, by now, you are clear how to write polymorphic method and as well as how to use. Let’s jump to how you can make the Runtime Polymorphism.

To continue the discussion, first we need to know that there are 2 basic types of polymorphism. They are, Overloading, referred as Compile time polymorphism, and Overriding also called as Run-Time polymorphism. What you have seen above is the first kind of polymorphism. The second type is referred as late binding. In other words, the selection of the method for execution at runtime depends on the reference of the actual object that is triggering the invoking of the method. Now let's explore that with some example.

Let us take a small class, as mentioned below with few properties. This class acts as a base class for us.

    public class EmpNames
    {
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
    }

We will now inherit this into the following classes. Observe that the both classes doesn't have any direct relation with each other and can be instantiated as is.

    /// <summary>
/// This class calculate the wages for given number of days
/// </summary>
public class Wages : EmpNames
{
/// <summary>
/// This will calculate the wages for the employees
/// </summary>
/// <param name="Params">Wage per Day, Number of Working days in a month</param>
/// <returns> WagePerDay * WorkingDays </returns>
public double CalculateSalary(ArrayList Params)
{
return double.Parse(Params[0].ToString()) * int.Parse(Params[1].ToString());
}
}


/// <summary>
/// This class will calculate the salary
/// </summary>
public class Salried : EmpNames
{
/// <summary>
/// This will calculate the salary for the employees
/// </summary>
/// <param name="Params">Working days Per Month, Leaves, Salary Per Month</param>
/// <returns> Full Salary in case no value for Leaves. Other case, (SalaryPerMonth/WorkingDays) * (WorkingDays - Leaves) </returns>
public double CalculateSalary(ArrayList Params)
{
double dSal=double.Parse(Params[2].ToString());
int intLeaves = int.Parse(Params[1].ToString());
if (!intLeaves.Equals(0))
{
int intWrkDays = int.Parse(Params[0].ToString());
dSal = (dSal / intWrkDays) * (intWrkDays - intLeaves);
}
return dSal;
}
}

Now that we have these two classes, We can write our code to instantiate them as individual. But the point of this post is to describe the "RunTime Polymorphism". Before we go further, note that, each class has the method "CalculateSalary" and as they are not directly related, you can instantiate them with out any hassle.

            EmpNames empObj;
            ArrayList alValues = new ArrayList();
alValues.Add(30); //Just add all the fields as this
            bool bSalaried = true; //am using this variable for validation of emp

if (bSalaried) //Validating whether Salaried or Wages
empObj = new Salried();
else
empObj = new Wages();
After executing the above lines of code, you are sure about the type of the variable empObj. This is Runtime initiating the object. But this is not the purpose of our current topic.
            double dVal;

//The below line will throw compile time error
//dVal = empObj.CalculateSalary(alValues);
dVal = ((Wages) empObj).CalculateSalary(alValues);

What do you see from the last line of the above code? Did you find that the method invoked is from a class type. Now, think that, what if the class is being instantiated as Salaried and the last line is being invoked?


This is called as RunTime Polymorphism.


del.icio.us Tags: , ,


-----------------------
 Declaimer: What ever you read here is out of my own experience. No one shall be made responsible for the contents and issues that are mentioned here. If you have something to share in person on this post, pl drop me a mail at dskcheck@gmail.com with the title in the subject.

Comments

Popular posts from this blog

Network Intrusion Detection using Supervised ML technique

Common mistakes by Interviewer

Keep the system active, to avoid the auto lock