Unit 4 · Association, Aggregation and Composition

4.4.3Self-check and practice

Self-check questions

Write your answers first, then open the answers to check them.

  1. What is the difference between inheritance (is-a) and composition (has-a)? Give an example of each.
  2. Why is Library–Book an aggregation but Book–Chapter a composition?
  3. In code, how can you tell composition from aggregation?
  4. What do the hollow and filled diamonds mean?
Show answers
  1. 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".

  2. 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 new in its constructor, keeps it in a private (often final) attribute and never shares it.
    • Aggregation: the part is created outside and passed in (through a constructor parameter or an add method). It may be shared and survives when the whole is gone.
  3. 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

  1. 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.

  2. Implement an Order class composed of OrderLine objects. Order calculates the total from its lines.
  3. Implement Team and Player as an aggregation. Show a player moving from one team to another.
  4. Draw class diagrams for exercises 2 and 3.
  5. 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.