GCSE Link: None

Association is another fundamental principle of OOP where objects can reference other objects.

For example, a Character object in a game might have references to the Weapons that it can use. It does not make sense to use inheritance here, since the two objects are not the same type as each other: instead they are linked by ownership.


There are two types of association, differentiated by the strength of the relationship:

Composition is the stronger form of association, where the contained objects cannot exist without the container.

For example: Attachment and Email. An Email object will keep track of the Attachments to that email, but the attachments cannot exist if the email is deleted. Therefore this is composition.

Aggregation is the weaker form of association, where the contained objects may exist outside of the container.

For example: Song and Playlist. A Playlist object will keep track of the Songss in that playlist, but the songs can still exist if the playlist is deleted. Therefore this is aggregation.



If you have a choice, which should you choose: composition or inheritance?

Composition should be favoured over inheritance. It allows relationships to be more flexible, therefore making code easier to maintain and extend.