Self-check questions
Write your answers first, then open the answers to check them.
- What is the difference between inheritance (is-a) and composition (has-a)? Give an example of each.
- Why is Library–Book an aggregation but Book–Chapter a composition?
- In code, how can you tell composition from aggregation?
- What do the hollow and filled diamonds mean?
Show answers
Inheritance (is-a) means a class is a special kind of another class and inherits its members:
Car extends Vehicle. Composition (has-a, part-of) means a class contains another object as a part that it creates and owns: a Car has an Engine. Test with the sentences "X is a Y" and "X has a Y".A Book exists on its own: it is created outside the library and can move to another library or outlive it, so Library–Book is aggregation. A Chapter belongs to exactly one Book and means nothing without it; it is created and destroyed with the book, so Book–Chapter is composition.
- Composition: the whole creates the part inside itself, usually with
newin its constructor, keeps it in aprivate(oftenfinal) attribute and never shares it. - Aggregation: the part is created outside and passed in (through a constructor parameter or an
addmethod). It may be shared and survives when the whole is gone.
- Composition: the whole creates the part inside itself, usually with
Both diamonds are drawn at the whole end of the line. A hollow diamond means aggregation: the parts can exist without the whole. A filled diamond means composition: the whole owns the parts and they are destroyed with it.
Practice exercises
- Classify each pair and justify: (a) Customer–Order, (b) University–Faculty, (c) Human–Heart, (d) Playlist–Song, (e) Invoice–InvoiceLine, (f) Teacher–Course.
Hint
(a) association, (b) aggregation, (c) composition, (d) aggregation, (e) composition, (f) association.
- Implement an Order class composed of OrderLine objects. Order calculates the total from its lines.
- Implement Team and Player as an aggregation. Show a player moving from one team to another.
- Draw class diagrams for exercises 2 and 3.
- A computer has a CPU, RAM and a keyboard. Decide which relationships are composition and which are aggregation, and write code.
Hint
The CPU and RAM are built in and created with the computer in this model, so composition; the keyboard is plugged in and can move to another computer, so aggregation.