CHAPTER 6 UNDERSTANDING INHERITANCE AND POLYMORPHISM
The Second Pillar of OOP: The Details of Inheritance
Now that you have seen the basic syntax of inheritance, let’s create a more complex example and get to
know the numerous details of building class hierarchies. To do so, you will be reusing the Employee class
you designed in Chapter 5. To begin, create a brand new C# Console Application named Employees.
Next, activate the Project Add Existing Item menu option and navigate to the location of your
Employee.cs and Employee.Internals.cs files you created in the EmployeeApp example of Chapter 5.
Select each of them (via a Ctrl+click) and click the Add button. Visual Studio responds by copying each
file into the current project.
Before you start to build some derived classes, you have one detail to attend to. Because the original
Employee class was created in a project named EmployeeApp, the class has been wrapped within an
identically named .NET namespace. Chapter 14 will examine namespaces in detail; however, for
simplicity, rename the current namespace (in both file locations) to Employees in order to match your
new project name:
// Be sure to change the namespace name in both C# files!
namespace Employees
{
partial class Employee
{...}
}
Note As a sanity check, compile and run your new project by pressing Ctrl+F5. The program will not do
anything at this point; however, this will ensure you do not have any compiler errors.
Your goal is to create a family of classes that model various types of employees in a company.
Assume that you want to leverage the functionality of the Employee class to create two new classes
(SalesPerson and Manager). The new SalesPerson class “is-an” Employee (as is a Manager). Remember that
under the classical inheritance model, base classes (such as Employee) are used to define general
characteristics that are common to all descendents. Subclasses (such as SalesPerson and Manager)
extend this general functionality while adding more specific functionality.
For your example, you will assume that the Manager class extends Employee by recording the number
of stock options, while the SalesPerson class maintains the number of sales made. Insert a new class file
(Manager.cs) that defines the Manager class with the following automatic property:
// Managers need to know their number of stock options.
class Manager : Employee
{
public int StockOptions { get; set; }
}
Next, add another new class file (SalesPerson.cs) that defines the SalesPerson class with a fitting
automatic property:
// Salespeople need to know their number of sales.
class SalesPerson : Employee
{
public int SalesNumber { get; set; }
220