Skip to content

Instantly share code, notes, and snippets.

@dnasca
Created March 17, 2015 06:38
Show Gist options
  • Select an option

  • Save dnasca/b3a05f6528fe0f36c3cc to your computer and use it in GitHub Desktop.

Select an option

Save dnasca/b3a05f6528fe0f36c3cc to your computer and use it in GitHub Desktop.
Polymorphism with virtual and override
using System;
/* Polymorphism with virtual and override
*
* Base class reference variables can point to a child class object
*
* !@!@ Polymorphism enables us to invoke derived class methods using a base class reference variable at RUN-TIME !@!@
*/
public class Employee
{
public string FirstName = "Derrik";
public string LastName = "Nasca";
public virtual void PrintFullName() //indicates to the derived classes that it can override this virtual method if they choose to do so
{
Console.WriteLine(FirstName + " " + LastName);
}
}
public class FullTimeEmployee : Employee
{
public override void PrintFullName()
{
Console.WriteLine(FirstName + " " + LastName + " - Full Time");
}
}
public class PartTimeEmployee : Employee
{
public override void PrintFullName()
{
Console.WriteLine(FirstName + " " + LastName + " - Part Time");
}
}
public class TemporaryEmployee : Employee
{
public override void PrintFullName()
{
Console.WriteLine(FirstName + " " + LastName + " - Temporary");
}
}
public class Program
{
public static void Main()
{
var employees = new Employee[4]; //create an array with 4 employee objects
//assign a child class object to a base class reference variable. each element of the array will be assigned a different type of employee object
employees[0] = new Employee();
employees[1] = new FullTimeEmployee();
employees[2] = new PartTimeEmployee();
employees[3] = new TemporaryEmployee();
foreach (Employee e in employees) //for each employee object in the employees array
{
e.PrintFullName(); //this will invoke the overriden PrintFullName method from each class during run-time
}
Console.ReadKey();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment