This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 2: Object interaction

Aggregation vs. composition

face Josiah Wang

In object-oriented analysis and design terminology, composition is actually defined as a stronger/stricter form of aggregation.

For composition, an object ‘part’ exists only for the ‘whole’ object, so it belongs exclusively to the object. For example, a Room instance can only be part of a specific House and not some other House, and it cannot exist without the House. The Head of the Hero belongs exclusively to the Hero, and cannot exist after the Hero perishes (well, in normal cases anyway). So strictly speaking, composition actually represents full ‘ownership’, or a “must-have-a” relationship.

For aggregation, the owner is less exclusive. A ‘part’ can exist independently of an object, and can belong to other objects as well. For example, a Weapon can exist even after a Hero has been destroyed. A Playlist can have many Songs, but the Songs are independent of the Playlist. A Band can have Members who can also be members of other things (and can even leave the band!)

To make things even more confusing, we have an even more general term called association which focusses on only the ‘has-a’ aspect and not the whole-part relationship. For example, a Road has Cars but does not quite ‘own’ the Cars. Or a Department has Teachers, but it does not ‘own’ the Teachers either (except by paid employment!)

But let’s not worry about the terminology. The distinction between the terms is probably not too important for practical use. For our course, I will use these terms interchangeably. So, when I say composition, aggregation or association, I usually just mean a “has-a” relationship in general.

In a class diagram, aggregation is represented with a line with a diamond. Composition has a filled diamond. Association is simply a solid line with no diamonds (not shown in this diagram).

Class diagram for aggregation/composition