CHAPTER 6 UNDERSTANDING INHERITANCE AND POLYMORPHISM
// store a Manager reference in an object variable just fine.
object frank = new Manager("Frank Zappa", 9, 3000, 40000, "111-11-1111", 5);
}
In the Employees example, Managers, SalesPerson, and PTSalesPerson types all extend Employee, so
you can store any of these objects in a valid base class reference. Therefore, the following statements are
also legal:
static void CastingExamples()
{
// A Manager "is-a" System.Object, so we can
// store a Manager reference in an object variable just fine.
object frank = new Manager("Frank Zappa", 9, 3000, 40000, "111-11-1111", 5);
// A Manager "is-an" Employee too.
Employee moonUnit = new Manager("MoonUnit Zappa", 2, 3001, 20000, "101-11-1321", 1);
// A PTSalesPerson "is-a" SalesPerson.
SalesPerson jill = new PTSalesPerson("Jill", 834, 3002, 100000, "111-12-1119", 90);
}
The first law of casting between class types is that when two classes are related by an “is-a”
relationship, it is always safe to store a derived object within a base class reference. Formally, this is
called an implicit cast, as “it just works” given the laws of inheritance. This leads to some powerful
programming constructs. For example, assume you have defined a new method within your current
Program class:
static void GivePromotion(Employee emp)
{
// Increase pay...
// Give new parking space in company garage...
Console.WriteLine("{0} was promoted!", emp.Name);
}
Because this method takes a single parameter of type Employee, you can effectively pass any
descendent from the Employee class into this method directly, given the “is-a” relationship:
static void CastingExamples()
{
// A Manager "is-a" System.Object, so we can
// store a Manager reference in an object variable just fine.
object frank = new Manager("Frank Zappa", 9, 3000, 40000, "111-11-1111", 5);
// A Manager "is-an" Employee too.
Employee moonUnit = new Manager("MoonUnit Zappa", 2, 3001, 20000, "101-11-1321", 1);
GivePromotion(moonUnit);
}
// A PTSalesPerson "is-a" SalesPerson.
SalesPerson jill = new PTSalesPerson("Jill", 834, 3002, 100000, "111-12-1119", 90);
GivePromotion(jill);
241