Lesson 9
No Object is an Island
Chapter 2: Object interaction
Aggregation vs. composition
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 Song
s, but the Song
s are independent of the Playlist
. A Band
can have Member
s 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 Car
s but do not quite ‘own’ the Car
s. Or a Department
has Teacher
s, but they do not ‘own’ the Teacher
s 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 does not have a diamond (not shown in this diagram).