Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Aggregation and Composition

Associations are only one type of relationship in UML. We will consider two more types of other UML relationships in this article and leave the others for a later time. Aggregation and composition relationships are really just different flavors of an association. An aggregation is a type of association that represents a relationship in which objects of one class represent parts of objects of another class; you will hear people referring to aggregation as a whole-part relationship. An aggregation relationship is shown by a solid line with an unfilled diamond at the end closest to the class that represents the "whole" in the relationship (see Figure 7).

Figure 7Figure 7 Aggregation and composition.

So, what does aggregation look like in Java source code? Well, the answer is, "It depends on who you ask." Aggregation is a somewhat vague concept that conveys a life-cycle dependency relationship. Some use the convention that aggregation means that the Whole class is responsible for creating and destroying (leaving for the garbage collector) the objects of the Part class. Others use the relationship far more loosely. In the end, it's probably best to explicitly agree on a convention in your own team to avoid confusion.

There is a stronger version of the aggregation relationship called composition. A composition relationship is the same as an aggregation except that a Part object can belong only to one Whole object at any one time. At least this time we know we have to write some code to check that constraint.

  • + Share This
  • 🔖 Save To Your Account