What is the difference between aggregation and composition in object oriented design?

Objects can be connected by association. This article describes two forms of association: aggregation and composition and the difference between them.

An association is a relationship between two classes, indicated by a line:

Aggregation and Composition are two forms of association

The following diagram shows a UML class diagram with three classes.

The solid diamond indicates Composition. Notice how teams belong to the single company object. If the company object is deleted, the teams will have no reason to exist anymore.

The open diamond indicates Aggregation. When a team is deleted, the employees that were in the team, still exist. Employees might also belong to multiple teams. A team object does not "own" an employee object.

No quantities in this example

The association alone does not indicate one-to-one or one-to-many relationship. For this, numbers or stars are added to the symbols. To keep the focus on the difference between aggregation and composition, I will not add numbers to the diagrams.

A second example

The next example shows a class diagram for a car factory.

A car needs a mechanic to work on it. A mechanic can also work on other cars at the same time. If a car object is deleted, the mechanic keeps working at the factory. In the diagram, this is indicated with the open diamond: aggregation.

The key class is connected with the solid diamond (composition). If the car object is deleted from the system, the key is useless and must be deleted also.

Where to put the diamond in the UML diagram?

The class that has the open diamond connected, is called the aggregate and is the class that consists of (non-exclusive) instances of the other class.

A class that has the solid diamond connected, is the composite and exclusively "owns" instances of the other class.

Summary

Aggregation and Composition are relationships between two classes.

An aggregate allows its aggregated objects to be used in other aggregates. If the aggregate is destroyed, its aggregates can live on in the system.

In composition, an object exclusively belongs to the composite object. When the composite object is destroyed, the parts that belong to it are destroyed too.

Written by Loek van den Ouweland on 2021-08-06. Questions regarding this artice? You can send them to the address below.