LOW-LEVEL DESIGN · MODELING AND UML · UML · 17 OF 48

UML Class Diagrams: Relationships and Multiplicity Explained

How to read and draw UML class diagrams for low-level design: the class box, visibility, association, aggregation, composition, inheritance, realization, dependency and multiplicity, each shown on a parcel locker system and mapped to Java code, plus a fast way to sketch one in an interview.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 15

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 159 lines, with a small main() demo. Save it as ParcelLockerDiagramDemo.java, then run javac ParcelLockerDiagramDemo.java && java ParcelLockerDiagramDemo.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A parcel locker system that matches the class diagram in this lesson.
 * Each relationship type is labelled where it appears in the code.
 */
public class ParcelLockerDiagramDemo {

    enum Size { SMALL, MEDIUM, LARGE }

    record Parcel(String id, Size size, String phone, boolean chilled) { }

    /** Realization: SmsNotifier implements this interface. */
    interface Notifier {
        void send(String phone, String message);
    }

    static final class SmsNotifier implements Notifier {
        @Override
        public void send(String phone, String message) {
            System.out.println("  SMS to " + phone + ": " + message);
        }
    }

    /** Dependency target: the station only receives it as a method parameter. */
    static final class PinGenerator {
        private int next = 4821;

        String nextPin() {
            return String.valueOf(next++);
        }
    }

    /** Association: a locker holds zero or one Parcel (multiplicity 0..1). */
    static class Locker {
        private final String code;
        private final Size size;
        private Parcel parcel;              // null when empty

        Locker(String code, Size size) {
            this.code = code;
            this.size = size;
        }

        boolean fits(Parcel p) {
            return parcel == null && !p.chilled() && p.size().ordinal() <= size.ordinal();
        }

        void store(Parcel p) {
            parcel = p;
        }

        Parcel takeOut() {
            Parcel p = parcel;
            parcel = null;
            return p;
        }

        String code() {
            return code;
        }

        Size size() {
            return size;
        }

        boolean empty() {
            return parcel == null;
        }
    }

    /** Inheritance: a cold locker is a locker that also accepts chilled parcels. */
    static final class ColdLocker extends Locker {
        ColdLocker(String code, Size size) {
            super(code, size);
        }

        @Override
        boolean fits(Parcel p) {
            return empty() && p.size().ordinal() <= size().ordinal();
        }
    }

    static final class LockerStation {
        private final List<Locker> lockers;          // composition: 1 station to 1..* lockers
        private final Notifier notifier;             // association
        private final Map<String, Locker> byPin = new HashMap<>();

        LockerStation(Notifier notifier) {
            this.notifier = notifier;
            // The station creates and owns its lockers; nobody else holds them.
            this.lockers = List.of(
                    new Locker("A1", Size.SMALL),
                    new Locker("A2", Size.MEDIUM),
                    new ColdLocker("C1", Size.MEDIUM),
                    new Locker("B1", Size.LARGE));
        }

        /** Dependency: PinGenerator is used here and not stored. */
        String deposit(Parcel p, PinGenerator pins) {
            for (Locker locker : lockers) {
                if (locker.fits(p)) {
                    locker.store(p);
                    String pin = pins.nextPin();
                    byPin.put(pin, locker);
                    notifier.send(p.phone(), "parcel " + p.id() + " is in " + locker.code() + ", pin " + pin);
                    return locker.code();
                }
            }
            return "none free";
        }

        Parcel pickUp(String pin) {
            Locker locker = byPin.remove(pin);
            if (locker == null) {
                throw new IllegalArgumentException("wrong pin");
            }
            return locker.takeOut();
        }
    }

    /** Aggregation: the route groups parcels that were created elsewhere and outlive it. */
    static final class CourierRoute {
        private final List<Parcel> parcels;

        CourierRoute(List<Parcel> parcels) {
            this.parcels = new ArrayList<>(parcels);
        }

        void deliverAll(LockerStation station, PinGenerator pins) {
            for (Parcel p : parcels) {
                System.out.println(p.id() + " -> locker " + station.deposit(p, pins));
            }
            parcels.clear();                          // route is done; parcels still exist
        }
    }

    public static void main(String[] args) {
        LockerStation station = new LockerStation(new SmsNotifier());
        PinGenerator pins = new PinGenerator();

        Parcel book = new Parcel("P-12", Size.SMALL, "98100-11111", false);
        Parcel insulin = new Parcel("P-13", Size.SMALL, "98100-22222", true);
        Parcel kettle = new Parcel("P-14", Size.MEDIUM, "98100-33333", false);

        new CourierRoute(List.of(book, insulin, kettle)).deliverAll(station, pins);

        Parcel collected = station.pickUp("4821");
        System.out.println("customer collected " + collected.id());
        try {
            station.pickUp("4821");
        } catch (IllegalArgumentException e) {
            System.out.println("second pickup refused: " + e.getMessage());
        }
    }
}

Notes

The problem

Here is the problem. You say the station has lockers, lockers have parcels, the courier also has parcels, and some lockers are cold. Every has is a different relationship, and none of the important questions are answered. Does a locker exist without its station? How many parcels can one locker hold? Is a cold locker a kind of locker, or something else? A class diagram answers all of these with a line and a number.

Said out loud
  • "The station has lockers,
  • lockers have parcels, the
  • courier has parcels too,
  • and some lockers are cold"
  • questions left open:
  • does a locker die with
  • the station?
  • how many parcels per locker?
  • is a cold locker a locker?

The class box

Start with one class box. It has three parts. The top holds the class name. The middle lists fields, written as name, colon, type. The bottom lists methods with their parameters and return type. A minus sign in front means private, plus means public, a hash means protected and a tilde means package private. Interfaces get the word interface above the name, and abstract names are written in italics.

One class box
+-----------------------------+
| Locker                      |
+-----------------------------+
| - code: String              |
| - size: Size                |
| - parcel: Parcel            |
+-----------------------------+
| + fits(p: Parcel): boolean  |
| + store(p: Parcel): void    |
+-----------------------------+
minus private, plus public

Association

The most common relationship is association, drawn as a plain solid line. It means one object keeps a reference to another and works with it over time. A locker holds a parcel. An arrowhead on the line shows the direction we can navigate: the locker knows its parcel, but the parcel does not know its locker. In Java, association is usually just a field of the other type.

Multiplicity

Multiplicity puts numbers at each end of a line. One means exactly one. Zero dot dot one means none or one. A star means any number, including zero. One dot dot star means at least one. So a station has one or more lockers, and a locker holds zero or one parcel. These numbers turn straight into code: zero dot dot one is a field that may be null, and a star is a list or a map.

Multiplicity
  • 1 exactly one
  • 0..1 none or one
  • * any number (0..*)
  • 1..* at least one
  • 2..4 between two and four
  • station 1 to 1..* lockers
  • locker 1 to 0..1 parcel

Whole and part

Two special kinds of association describe a whole and its parts. Composition, a filled diamond on the whole's side, means strong ownership. The station creates its lockers, and if the station is removed, its lockers go too. Each locker belongs to one station only. Aggregation, a hollow diamond, is a loose grouping. A courier route groups today's parcels, but when the route ends, the parcels still exist. If you are unsure, a plain association is always acceptable.

Two kinds of whole-part
  • composition: filled diamond
  • station creates its lockers
  • remove station, lockers go
  • a part has one owner
  • aggregation: hollow diamond
  • a route groups parcels
  • route ends, parcels remain
  • parts can be shared

Inheritance

Inheritance, also called generalization, is a solid line with a hollow triangle pointing at the parent class. ColdLocker extends Locker. A cold locker is a locker, so it can be used anywhere a locker is expected, and it changes one rule: it also accepts chilled parcels like medicine or groceries. The triangle always points up, toward the more general class. Check the is a test before you draw it.

Realization

Realization is how a class implements an interface. It looks like inheritance but the line is dashed: a dashed line with a hollow triangle pointing at the interface. SmsNotifier realizes the Notifier interface. Tomorrow an email notifier or a push notifier can realize it too. In the diagram the interface is marked with the word interface in double angle brackets above its name.

Dependency

Dependency is the weakest relationship, a dashed line with an open arrowhead. It means one class uses another briefly, as a method parameter, a local variable or a return type, but does not keep it in a field. The station's deposit method receives a PinGenerator, asks it for one pin, and lets it go. If PinGenerator changes, the station might be affected, which is all a dependency arrow promises.

The whole diagram

Put together, the whole design fits on one screen. The station owns one or more lockers by composition, keeps a Notifier by association, and uses a PinGenerator during deposit. ColdLocker extends Locker. SmsNotifier realizes Notifier. Each locker holds zero or one parcel, and a courier route aggregates parcels. An interviewer can now see ownership, choices and counts before you write a single line.

Diagram to code

Each line type maps to plain Java. Composition: the station creates its lockers inside its constructor and never hands them out for others to own. Association: a field, like the notifier. Dependency: only a method parameter, like the pin generator in deposit. Inheritance is extends, realization is implements. Aggregation is a field holding objects that were created elsewhere and passed in, like the route's list of parcels.

Diagram to Java
// composition: created inside
lockers = List.of(new Locker(..), ...)
// association: a field
private final Notifier notifier;
// dependency: only a parameter
String deposit(Parcel p, PinGenerator g)
// inheritance
class ColdLocker extends Locker
// realization
class SmsNotifier implements Notifier

Run it

Watch one deposit. The courier, working through the route's parcels, hands parcel P twelve to the station. The station walks its own lockers, finds the first one that fits, and stores the parcel there. It asks the pin generator for a fresh pin, keeps the pin against that locker, and tells the notifier to text the pin to the customer. Every arrow in the diagram was used once.

Drawing it fast

In an interview, draw it in layers. First, boxes with just the names of the main nouns. Second, the lines: is it a kind of, does it own, or does it just use. Third, numbers on the important ownership lines. Fourth, only the fields and methods that carry business rules, like fits and deposit. Fifth, mark the policies that might change as interfaces. Skip getters, setters and every private detail. A clear sketch beats a complete one.

Interview recipe
  • 1 boxes for the main nouns
  • (name only at first)
  • 2 lines: is-a, has-a, uses
  • 3 numbers on key has-a lines
  • 4 add the few fields and
  • methods that carry rules
  • 5 interfaces for policies
  • skip getters, setters and
  • every private field

Common mistakes

Watch for the usual mistakes. The triangle always points at the parent or interface, never at the child. Do not use inheritance for has a relationships: a station is not a locker. Do not put filled diamonds on everything; most relationships are plain associations. Always add numbers on the key lines. And do not list every getter. When you are unsure which symbol fits, a plain line with a clear label is better than a wrong symbol.

Watch out for
  • triangle pointing at the
  • child (it points at parent)
  • inheritance for "has-a"
  • (a Station is not a Locker)
  • composition everywhere
  • missing multiplicity
  • too much detail, no story
  • when unsure: plain line
  • plus a label

Interview questions

What is the difference between aggregation and composition?

Both are whole-part relationships. In composition (filled diamond) the whole owns its parts exclusively and they share its lifetime, like a locker station and its lockers. In aggregation (hollow diamond) the parts can exist independently and may be shared, like parcels grouped on a courier route.

How do you show inheritance versus interface implementation in UML?

Both use a hollow triangle pointing at the parent type. Inheritance (generalization) uses a solid line, as in extends; realization uses a dashed line, as in implements. Interfaces are also marked with the interface stereotype above the name.

What is the difference between association and dependency?

An association is a lasting structural link, usually a field that holds a reference to the other object. A dependency is a weaker, temporary use, such as a method parameter, local variable or return type, drawn as a dashed arrow.

What does multiplicity mean in a class diagram?

The numbers at the ends of an association that say how many objects take part, such as 1, 0..1, * or 1..*. They map directly to code: 0..1 is a field that may be empty, and * or 1..* is a collection.

What do the symbols plus, minus and hash mean in a class box?

They show visibility: plus is public, minus is private, hash is protected and tilde is package-private. Static members are underlined and abstract ones are in italics.

How detailed should a class diagram be in a design interview?

Detailed enough to show the main entities, how they relate, who owns what and how many, plus the methods that carry business rules and the interfaces for changing policies. Skip getters, setters and private plumbing; clarity matters more than completeness.

How does composition show up in Java code?

The whole creates its parts itself, usually in its constructor, keeps them in private fields and does not hand them out for others to own. When the whole is no longer referenced, the parts become unreachable with it.

When should you draw an arrowhead on an association?

When navigation is one way, meaning only one side holds a reference to the other. A locker that knows its parcel but a parcel that does not know its locker is a directed association from Locker to Parcel.