CHAPTER 6 UNDERSTANDING INHERITANCE AND POLYMORPHISM
static void Main(string[] args)
{
...
// Define my benefit level.
Employee.BenefitPackage.BenefitPackageLevel myBenefitLevel =
Employee.BenefitPackage.BenefitPackageLevel.Platinum;
Console.ReadLine();
}
Excellent! At this point, you have been exposed to a number of keywords (and concepts) that allow
you to build hierarchies of related types via classical inheritance, containment, and nested types. If the
details aren’t crystal clear right now, don’t sweat it. You will be building a number of additional
hierarchies over the remainder of this book. Next up, let’s examine the final pillar of OOP:
polymorphism.
The Third Pillar of OOP: C#’s Polymorphic Support
Recall that the Employee base class defined a method named GiveBonus(), which was originally
implemented as follows:
public partial class Employee
{
public void GiveBonus(float amount)
{
Pay += amount;
}
...
}
Because this method has been defined with the public keyword, you can now give bonuses to
salespeople and managers (as well as part-time salespeople):
static void Main(string[] args)
{
Console.WriteLine("***** The Employee Class Hierarchy *****\n");
// Give each employee a bonus?
Manager chucky = new Manager("Chucky", 50, 92, 100000, "333-23-2322", 9000);
chucky.GiveBonus(300);
chucky.DisplayStats();
Console.WriteLine();
}
SalesPerson fran = new SalesPerson("Fran", 43, 93, 3000, "932-32-3232", 31);
fran.GiveBonus(200);
fran.DisplayStats();
Console.ReadLine();
The problem with the current design is that the publicly inherited GiveBonus() method operates
identically for all subclasses. Ideally, the bonus of a salesperson or part-time salesperson should take
into account the number of sales. Perhaps managers should gain additional stock options in conjunction
with a monetary bump in salary. Given this, you are suddenly faced with an interesting question: “How
can related types respond differently to the same request?” Again, glad you asked!
228