Click here to Skip to main content
15,881,757 members
Articles / Programming Languages / C#

Runtime Polymorphism - Simplified

Rate me:
Please Sign up or sign in to vote.
4.72/5 (22 votes)
3 Sep 2014CPOL4 min read 49.4K   18   17
Runtime polymorphism - simplified

Introduction

Polymorphism is a wide concept which is used across the application for bringing in feature of OOPs.

Polymorphism is of two types, static (compile time) and dynamic polymorphism (run time). We will deal with what is run time polymorphism and its implementation as it is a big and an important concept of OOPs and a widely asked question.

Background

Now before understanding what is runtime polymorphism, let's know about abstract class, it is the blue print of the problem and it contains abstract methods (partial + complete methods).

Assume from the below figure that Employee is an abstract class and we are trying to build an application for College. Therefore, Employee has properties such as Id, Name and Salary Per Day which are fields in Class. While Lab assistant, Lecturer and Admin are the Type of Employee. These type of employee will inherit all the details of abstract Class Employee, therefore Id, Name and salary per day are properties of Lab assistant, Lecturer and Admin.

We have other methods like Display() and Cal_Salary() which will perform operations on Id, Name and salary of each employee; which will either display or calculate details.

Therefore:

  • Display(): This method is treated as Virtual method
  • Cal_Salary(): This method is Abstract method, which means either implementation can be partial or complete. Here, calculation for each employee varies based on salary structure. Therefore, it's just a blue print, not complete implementation for employee. We can implement the method and write further implementation for each employee.

Image 1

Using the Code

Now let's try to implement the code based on the above interpretation.

Below are the details about Employee class in code form:

Image 2

Now, let's create Employees: Lab Assistant class.

In the below class, we have used base keyword to initialize the base class variables in base class itself. While LabNo is initialized here in Lab assistant constructor, display() is directly overridden as there is no functionality and helps in displaying initialized field in derived class (i.e.) LabNo.

Image 3

Now how to evaluate the details of Lab assistant:

Just create a reference for employee class and pass it as object to LabAssistant class.

Image 4

On press, F5 below is the OUTPUT;

Image 5

Therefore, it has displayed all the LabAssistant details with gross salary details.

Similarly, we can create for Lecturer and Admin.

For Lecturer, LabNo is replayed by Subject and HRA is 20% of basic salary.

The code is as below:

Image 6

For Admin, there is no property other than base class properties and HRA is 15% of basic salary. Therefore, the code goes as below:

Image 7

We will give choice to the end user to select the employee type and storing choice in variable "ch" as in below code:

Image 8

When user enters their choice, we will create object for type of employee on the fly as in the below code:

Image 9

Image 10

Further, we don't know which method is going to be called at compile time. It's completely end user choice dependent (i.e.) if User enters.

Choice 1 will give details of lab assistant.

Choice 2 its lecturer.

Image 11

Choice 3 its Admin.

Image 12

These details will be known at runtime and reference for employee will be created and assigned as object to respective choice given by user. This is the basic concept of run time polymorphism through implementation.

Live example we use is Microsoft Paint where a class is reference of class diagram and if we click drag and drop; it is going to select the area, because our reference becomes select area.

Image 13

Now, we’ll make it an object of circle and we’ll execute the same method click drag and drop and try to draw a circle.

Image 14

Because now our object reference is circle, if we select on rectangle, now our object reference becomes rectangle. And performing the same method click drag drop.

Image 15

From the above, we can draw a conclusion that object is created at runtime based on what we select like line or magnifier, etc. Therefore, Microsoft Paint is working on runtime polymorphism. We see that we are calling single method, but it's calling various tasks depending upon the object that it makes at runtime. This is nothing but Runtime Polymorphism real-time example.

Point of Interest

  • Runtime polymorphism is, if we have an abstract class and n number of classes which are implementing the abstract class and we’re making the reference of abstract class and making it an object of any class at runtime and calling the methods.
  • The method's code is referenced at runtime depending upon the users' input.
  • Runtime in the sense at the time of execution.
  • Polymorphism means many meanings and calculate salary has many meanings. It calculates the salary of admin, lectures and lab assistant, but at runtime.
  • At compile time, we cannot say what method is going to execute.
  • So this is all about runtime polymorphism.

The Code

C#
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;

namespaceRuntimePolymorphismEg
{
    abstract class Employee
    {
     protected int EmpId;
     protected string EmpName;
     protected double SalPerDay;

     public Employee(int EmpId, string EmpName, double SalPerDay)
     {
      this.EmpId = EmpId;
      this.EmpName = EmpName;
      this.SalPerDay = SalPerDay;
     }

     public virtual void Display()
     {
      Console.WriteLine("EmpId : " + EmpId);
      Console.WriteLine("EmpName : " + EmpName);
      Console.WriteLine("Emp Sal Per Day : " + SalPerDay);
     }

     public abstract void CalculateSalary(int days);
    }

    classLab Assistant : Employee
    {
     protected int LabNo;
     public LabAssistant(int EmpId, string EmpName, double SalPerDay,int LabNo):base(EmpId,EmpName,SalPerDay)
     { 
      this.LabNo = LabNo;
     }

     public override void Display()
     {
      base.Display();
      Console.WriteLine("LabNo :" + LabNo);
     }

     public override void CalculateSalary(int days)
     {
      double GS = SalPerDay * days;
      Console.WriteLine("Gross Salary is :"+GS);
     }
    }

   class Lecturer : Employee
   {
    protected string Sub;
    public Lecturer(int EmpId, string EmpName, double SalPerDay, string Sub)
            : base(EmpId, EmpName, SalPerDay)
    {
     this.Sub = Sub;
    }

    public override void Display()
    {
     base.Display();
     Console.WriteLine("Sub :" + Sub);
    }

    public override void CalculateSalary(int days)
    {
     double GS = (SalPerDay * days)+((SalPerDay * days)*20/100);
     Console.WriteLine("Gross Salary is :" + GS);
    }
   }

   class Admin : Employee
   {
    public Admin(int EmpId, string EmpName, double SalPerDay) : base(EmpId, EmpName, SalPerDay)
    {
    }

    public override void CalculateSalary(int days)
    {
     double GS = (SalPerDay * days) + ((SalPerDay * days) * 15 / 100);
     Console.WriteLine("Gross Salary is :" + GS);
    }
   }

   class Program
   {
    static void Main(string[] args)
    {
     Employee E;
     E = newLabAssistant(123, "Peter", 67.7, 34);
     Console.WriteLine("Enter You Choice");
     Console.WriteLine("1.LabAssistant 2.Lecturer 3.Admin 4.Exit");
     int ch = int.Parse(Console.ReadLine());

     switch (ch)
     {
      case 1:
      E = newLabAssistant(123, "Peter", 67.7, 34);
      break;
      
      case 2:
      E = newLecturer(124, "Tom", 89.6, "MS.Net");
      break;
     
      case 3:
      E = newAdmin(126, "Lilly", 45.8);
      break;

      case 4:
      System.Threading.Thread.CurrentThread.Abort();
      break;

      default:
      break;
     }

     E.Display();
     E.CalculateSalary(25);

     Console.ReadLine();
    }
   }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder ManzoorTheTrainer.com
India India
Manzoor is a Microsoft Certified Trainer who has been working on MS .Net technologies for more than a decade. Apart from development he is also passionate about delivering training on various MS .Net technologies and he has 10+ years of experience as a software development teacher. He writes articles for code-project as well. His YouTube channel has 1 million hits. He is the founder of ManzoorTheTrainer portal.

"I focus on simplifying, complex concepts..." - ManzoorTheTrainer

Founder of www.ManzoorTheTrainer.com [Free .net video tutorials on MS SQL Server, Asp.Net, C#.Net, Ado.Net, Entity Framework, MVC, Web Services, Android]

Comments and Discussions

 
Questionhow to achieve Runtime polymorhpism via properties Pin
Akhil Jain24-Jun-17 22:37
Akhil Jain24-Jun-17 22:37 
Questionrun time polymorphism. Pin
raees.qureshi16-Jul-16 5:28
raees.qureshi16-Jul-16 5:28 
GeneralMy vote of 5 Pin
Renju Vinod15-Oct-14 20:20
professionalRenju Vinod15-Oct-14 20:20 
GeneralRe: My vote of 5 Pin
Mohd Manzoor Ahmed15-Oct-14 20:26
professionalMohd Manzoor Ahmed15-Oct-14 20:26 
QuestionSome thoughts Pin
Nelek10-Oct-14 3:48
protectorNelek10-Oct-14 3:48 
AnswerRe: Some thoughts Pin
Mohd Manzoor Ahmed11-Oct-14 7:40
professionalMohd Manzoor Ahmed11-Oct-14 7:40 
GeneralRe: Some thoughts Pin
Nelek11-Oct-14 8:07
protectorNelek11-Oct-14 8:07 
QuestionGood Example Pin
Anil Srivastava14-Sep-14 21:21
Anil Srivastava14-Sep-14 21:21 
AnswerRe: Good Example Pin
Mohd Manzoor Ahmed15-Sep-14 15:41
professionalMohd Manzoor Ahmed15-Sep-14 15:41 
GeneralYap simple it is... Pin
Rehman Ahmad Ch4-Sep-14 6:23
Rehman Ahmad Ch4-Sep-14 6:23 
GeneralRe: Yap simple it is... Pin
Mohd Manzoor Ahmed4-Sep-14 6:31
professionalMohd Manzoor Ahmed4-Sep-14 6:31 
Thanks Abd Rehman Thumbs Up | :thumbsup:
Mohd Manzoor Ahmed [MCT]

GeneralMy vote of 5 Pin
Humayun Kabir Mamun3-Sep-14 21:11
Humayun Kabir Mamun3-Sep-14 21:11 
GeneralRe: My vote of 5 Pin
Mohd Manzoor Ahmed4-Sep-14 6:30
professionalMohd Manzoor Ahmed4-Sep-14 6:30 
GeneralMy vote of 5 Pin
Member 87919803-Sep-14 21:04
Member 87919803-Sep-14 21:04 
GeneralRe: My vote of 5 Pin
Mohd Manzoor Ahmed4-Sep-14 6:29
professionalMohd Manzoor Ahmed4-Sep-14 6:29 
GeneralSimplified... really? Pin
Paulo Zemek3-Sep-14 9:05
mvaPaulo Zemek3-Sep-14 9:05 
GeneralRe: Simplified... really? Pin
Mohd Manzoor Ahmed3-Sep-14 23:15
professionalMohd Manzoor Ahmed3-Sep-14 23:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.