C# Tutorial - Aggregation and Composition

posted Jun 28, 2011, 7:33 PM by magic stone   [ updated Jun 28, 2011, 7:35 PM ]

When do you make an object inherit from another object and when do you make an object become part of another object? So far we have looked at inheritance, but object oriented programming also includes another method for relationships between classes, that is when one object forms part of another object.

Aggregation and composition are very similar in nature. These relationships form a whole-part relationship that you can use to decompose objects into more manageable entities. The difference between aggregation and composition is that any object that can exist and be used independently uses aggregation, and an object that has no meaning outside of the relationship uses composition.

For example, a class named Car would have an engine. More importantly, we can recognize objects that fall into this relationship by the use of the term "is a part of", whereas inheritance uses the term "is a kind of". So back to our example, "an engine is a part of a car".

In UML, an object relationship that is formed by aggregation is drawn using an empty diamond. An object relationship that is formed using composition is drawn using a filled diamond.

The following UML diagram illustrates the concepts of aggregation and composition.


In the diagram above, the battery and the engine have no meaning outside of the car, as the car cannot work without either of them, so the relationship is formed using composition. However, a car can work without doors, so the relationship is formed using aggregation.

Coding Aggregation and Composition

From the previous diagram, we can create a possible small code sample that shows the two forms of relationship.

namespace MyCars
{
  public class Car
  {
    // Aggregation uses instances of objects created outside of
    // this class
    protected Door _frontRight;
    protected Door _frontLeft;
    protected Door _rearRight;
    protected Door _rearLeft;

    // inner classes used to create objects that are intrinsically
    // linked to the class Car
    protected class Engine
    {
      public int _horsePower;
    }

    protected class Battery
    {
      public int _voltage;
    }

    // Composition uses instances of objects that are created as
    // part of this object
    protected Engine _theEngine;
    protected Battery _theBattery;
  }

  public class Door
  {
    public int _position;
  }
}

By giving each of the members protected access modifiers, each class that inherits from Car has access to each of the members of the class Car.

namespace MyCars
{
  // Inherit from class Car
  public class FordCapri : Car
  {
    public FordCapri()
    {
      _theEngine._horsePower = 2000;
    }
  }
}
Comments