Skip to the guide

How classes relate: association, aggregation, composition and dependency

BeginnerConcept6 pages

Classes in a design connect in four ways. One class can know another, hold parts that may be shared, own a part outright, or use another class during one call. Interviewers want every line on your class diagram to match a field or a parameter in your code, and they listen for one sentence on who looks after each part's life.

A choir and its singers

A community choir meets every Tuesday evening. Its singers also sing in other choirs, and they were singers before this choir started and will still be singers after it ends. The choir keeps its own register of who came to each rehearsal. Nobody else writes in it, and when the choir closes, the register goes with it. The choir knows its conductor by name, and a new conductor can take over halfway through the season. At the end of the season, the choir prints each singer a card with her rehearsals and the conductor's name, hands it over and keeps no copy.

In code, the choir is a Project at a software company, and the singers are Employee objects. The singers are the choir's members, its parts, so they are aggregation: a project has its members, even though each one also works on other projects and outlives this one. The register is the project's Timesheet, which the project builds and never hands out, and that is composition. The conductor is the Manager, a plain association: she leads the project but isn't one of its parts, so the project only knows her. The printed card is a dependency, because summaryFor builds a Summary, returns it and keeps nothing.