CHAPTER 6 UNDERSTANDING INHERITANCE AND POLYMORPHISM
Programming for Containment/Delegation
Recall that code reuse comes in two flavors. You have just explored the classical “is-a” relationship.
Before you examine the third pillar of OOP (polymorphism) , let’s examine the “has-a” relationship (also
known as the containment/delegation model or aggregation). Assume you have created a new class that
models an employee benefits package, as follows:
// This new type will function as a contained class.
class BenefitPackage
{
// Assume we have other members that represent
// dental/health benefits, and so on.
public double ComputePayDeduction()
{
return 125.0;
}
}
Obviously, it would be rather odd to establish an “is-a” relationship between the BenefitPackage
class and the employee types. (Employee “is-a” BenefitPackage? I don’t think so.) However, it should be
clear that some sort of relationship between the two could be established. In short, you would like to
express the idea that each employee “has-a” BenefitPackage. To do so, you can update the Employee
class definition as follows:
// Employees now have benefits.
partial class Employee
{
// Contain a BenefitPackage object.
protected BenefitPackage empBenefits = new BenefitPackage();
...
}
At this point, you have successfully contained another object. However, to expose the functionality
of the contained object to the outside world requires delegation. Delegation is simply the act of adding
public members to the containing class that make use of the contained object’s functionality.
For example, you could update the Employee class to expose the contained empBenefits object using
a custom property, as well as make use of its functionality internally using a new method named
GetBenefitCost():
public partial class Employee
{
// Contain a BenefitPackage object.
protected BenefitPackage empBenefits = new BenefitPackage();
// Expose certain benefit behaviors of object.
public double GetBenefitCost()
{ return empBenefits.ComputePayDeduction(); }
// Expose object through a custom property.
public BenefitPackage Benefits
{
get { return empBenefits; }
set { empBenefits = value; }
225