CHAPTER 5 UNDERSTANDING ENCAPSULATION
Figure 5-4. The “is-a” relationship
There is another form of code reuse in the world of OOP: the containment/delegation model also
known as the “has-a” relationship or aggregation. This form of reuse is not used to establish parent/child
relationships. Rather, the “has-a” relationship allows one class to define a member variable of another
class and expose its functionality (if required) to the object user indirectly.
For example, assume you are again modeling an automobile. You might want to express the idea
that a car “has-a” radio. It would be illogical to attempt to derive the Car class from a Radio, or vice versa
(a Car “is-a” Radio? I think not!). Rather, you have two independent classes working together, where the
Car class creates and exposes the Radio’s functionality:
class Radio
{
public void Power(bool turnOn)
{
Console.WriteLine("Radio on: {0}", turnOn);
}
}
class Car
{
// Car 'has-a' Radio.
private Radio myRadio = new Radio();
public void TurnOnRadio(bool onOff)
{
// Delegate call to inner object.
myRadio.Power(onOff);
}
}
Notice that the object user has no clue that the Car class is making use of an inner Radio object.
static void Main(string[] args)
{
// Call is forwarded to Radio internally.
186