SyntaxPilot
Courses/Low-Level Design/Lesson 18

Low-Level Design · Lesson 18 of 90 · 11 min

UML 1: class diagrams you actually need

UMLclass diagramclass boxattributesoperationsvisibility markers + - # ~static and abstract notationinterface notationstereotypesassociation lineaggregation diamondcomposition diamondinheritance arrowrealization arrow

These are the notes for Low-Level Design (LLD) episode 18: UML class diagrams. A vague sentence in a design note causes a real bug, and a diagram is the fix. You'll learn the class box (attributes, operations, visibility, static, abstract, interfaces, stereotypes) and every relationship line: association, navigability, multiplicity, aggregation, composition, inheritance, realization and dependency, each mapped to Java code that was actually run with javac Main.java && java -cp . Main (Java 21). Outputs and error messages are real.

1. The real-life problem: a house built from a phone call

A man phones a builder: "two rooms and a kitchen". The builder fills every gap with a guess (where's the door? which wall is shared?), and the finished kitchen opens into the bathroom. Nobody said it shouldn't. That's why builders use blueprints: drawings with standard symbols that every builder reads the same way.

2. The problem in code: "an Order has lines"

The design note for a restaurant app said one sentence: an order has lines. A developer wrote an Order that just keeps whatever list it is given:

import java.util.*;

class Order {                          // spec said only: "an Order has lines"
    final String id;
    final List<String> lines;
    Order(String id, List<String> lines) { this.id = id; this.lines = lines; }   // keeps the caller's list
}
public class Main {
    public static void main(String[] args) {
        List<String> basket = new ArrayList<>(List.of("Dosa x2"));
        Order first = new Order("A1", basket);
        basket.add("Vada x1");                         // the waiter reuses the basket
        Order second = new Order("A2", basket);
        second.lines.add("Coffee x1");
        System.out.println(first.id + " lines: " + first.lines);
        System.out.println(second.id + " lines: " + second.lines);
    }
}
A1 lines: [Dosa x2, Vada x1, Coffee x1]
A2 lines: [Dosa x2, Vada x1, Coffee x1]

Order A1 now contains a vada and a coffee it never ordered: both orders share one list. The sentence never said whether an order owns its lines or just points to someone else's. A diagram says it with one symbol (the filled diamond, section 7).

3. UML: the blueprint language for code

UML (Unified Modeling Language) is a standard drawing language for software designs.

  • Developed at Rational Software in 1994-1995 by Grady Booch and James Rumbaugh, joined by Ivar Jacobson in 1995: three rival notations, unified.
  • Adopted as a standard by the Object Management Group (OMG) in 1997; published by ISO (the International Organization for Standardization) in 2005. The latest version is UML 2.5.1 (December 2017).
  • Two families of diagrams: structural (what exists: class, object, component, package diagrams) and behavioural (what happens over time: sequence, use-case, activity, state diagrams; next episode).

A class diagram is the structural diagram that shows classes, their members, and how they relate.

4. The class box

Every class is a box with three compartments: the name, the attributes (UML's word for fields), and the operations (UML's word for methods).

abstract class Account {                          // abstract: drawn in italics
    public final String owner;                    // +  public
    private double balance;                       // -  private
    protected String branch = "Pune";             // #  protected
    int pin = 1234;                               // ~  package-private
    static int count = 0;                         // underlined: static

    Account(String owner) { this.owner = owner; count++; }
    public void deposit(double amt) { balance += amt; }
    public double getBalance() { return balance; }
    abstract double interestRate();               // abstract operation: italics
}
class Savings extends Account {
    Savings(String owner) { super(owner); }
    double interestRate() { return 0.04; }
}
public class Main {
    public static void main(String[] args) {
        Account a = new Savings("Asha");
        a.deposit(500);
        System.out.println(a.owner + " has " + a.getBalance() + " at " + a.interestRate());
        System.out.println("accounts made: " + Account.count);
    }
}
Asha has 500.0 at 0.04
accounts made: 1

Drawn as UML:

┌──────────────────────────────────┐
│            «abstract»            │
│             /Account/            │   ← abstract: name in italics
├──────────────────────────────────┤
│ + owner: String                  │
│ - balance: double                │
│ # branch: String                 │
│ ~ pin: int                       │
│ + count: int        (underlined) │   ← static: underlined
├──────────────────────────────────┤
│ + deposit(amt: double): void     │
│ + getBalance(): double           │
│ ~ /interestRate(): double/       │   ← abstract operation: italics
└──────────────────────────────────┘

Attribute and operation syntax

Element Syntax Example
Attribute visibility name: Type [= default] - balance: double
Operation visibility name(param: Type, ...): ReturnType + deposit(amt: double): void

Visibility markers

Sign Visibility Java keyword Who can use it
+ public public everyone
- private private only the class itself
# protected protected subclasses (and the same package, in Java)
~ package (no keyword) classes in the same package

The minus sign is a promise the compiler keeps:

abstract class Account {                          // abstract: drawn in italics
    public final String owner;                    // +  public
    private double balance;                       // -  private
    protected String branch = "Pune";             // #  protected
    int pin = 1234;                               // ~  package-private
    static int count = 0;                         // underlined: static

    Account(String owner) { this.owner = owner; count++; }
    public void deposit(double amt) { balance += amt; }
    public double getBalance() { return balance; }
    abstract double interestRate();               // abstract operation: italics
}
class Savings extends Account {
    Savings(String owner) { super(owner); }
    double interestRate() { return 0.04; }
}
public class Main {
    public static void main(String[] args) {
        Account a = new Savings("Asha");
        a.deposit(500);
        System.out.println(a.owner + " has " + a.getBalance() + " at " + a.interestRate());
        System.out.println("accounts made: " + Account.count);
        a.balance = 1_000_000;                    // try to break the "-" rule
    }
}
Main.java:23: error: balance has private access in Account
        a.balance = 1_000_000;                    // try to break the "-" rule
         ^
1 error

Static and abstract

  • Static members (belong to the class, not each object) are underlined: count.
  • Abstract classes and operations are in italics. Since italics are easy to miss on a whiteboard, people also write {abstract} or the stereotype «abstract».

Interfaces and stereotypes

A stereotype is a word in guillemets (« ») above the name that marks a special kind of class: «interface», «enum», «abstract», or your own («controller», «composition root»). An interface box usually has only operations.

You don't have to show everything. A diagram shows what its reader needs; in an interview, draw class names and key operations first, and fields only where they matter.

5. Association, navigability and multiplicity

  • Association: one class holds a reference to another (usually a field). Drawn as a solid line. Order has a customer field.
  • Navigability: an open arrowhead shows which side knows the other. Order ──▶ Customer means the order can reach its customer, but the customer has no list of orders. No arrowheads usually means "both ways" or "not decided yet".
  • Multiplicity: numbers at each end saying how many objects can be at that end.
Multiplicity Meaning Example
1 exactly one each order has 1 customer
0..1 optional a seat has 0..1 passenger
* (or 0..*) zero or more a customer has * orders
1..* at least one an order has 1..* lines
2..4 a range a car has 2..4 doors

Read multiplicities across the line: in Order * ──▶ 1 Customer, the 1 next to Customer means each order has one customer; the * next to Order means a customer can have any number of orders.

Multiplicity is a rule the code should enforce:

import java.util.*;

class OrderLine { final String item; OrderLine(String i) { item = i; } }
class Order {                                        // diagram: Order 1 ◆── 1..* OrderLine
    private final List<OrderLine> lines = new ArrayList<>();
    Order(String... items) {
        if (items.length == 0) throw new IllegalArgumentException("an order needs at least 1 line");
        for (String i : items) lines.add(new OrderLine(i));
    }
    int size() { return lines.size(); }
}
public class Main {
    public static void main(String[] args) {
        System.out.println("lines: " + new Order("Poha", "Chai").size());
        System.out.println("lines: " + new Order().size());
    }
}
lines: 2
Exception in thread "main" java.lang.IllegalArgumentException: an order needs at least 1 line
    at Order.<init>(Main.java:7)
    at Main.main(Main.java:15)

6. Two kinds of has-a: composition and aggregation

Composition ◆ Aggregation ◇
Real life A house and its rooms: demolish the house, the rooms go too A school's Red House team and its students: disband it, students stay
Ownership The whole owns the part; a part belongs to one whole The whole groups parts it doesn't own; parts can be shared
Lifetime The part dies with the whole The part outlives the whole
In Java The whole creates the part and never hands it out The part is passed in from outside
Symbol filled diamond at the owner hollow diamond at the whole

Composition: the fix for our bug

import java.util.*;

class OrderLine {
    final String item; final int qty;
    OrderLine(String item, int qty) { this.item = item; this.qty = qty; }
    public String toString() { return item + " x" + qty; }
}
class Order {                                      // composition: the order owns its lines
    final String id;
    private final List<OrderLine> lines = new ArrayList<>();   // created here, never shared
    Order(String id) { this.id = id; }
    void add(String item, int qty) { lines.add(new OrderLine(item, qty)); }
    List<OrderLine> lines() { return List.copyOf(lines); }      // callers get a read-only copy
}
public class Main {
    public static void main(String[] args) {
        Order first = new Order("A1");
        first.add("Dosa", 2);
        Order second = new Order("A2");
        second.add("Vada", 1);
        second.add("Coffee", 1);
        System.out.println(first.id + " lines: " + first.lines());
        System.out.println(second.id + " lines: " + second.lines());
    }
}
A1 lines: [Dosa x2]
A2 lines: [Vada x1, Coffee x1]

The order creates its own list, never takes someone else's, and returns only a read-only copy (List.copyOf).

Aggregation

import java.util.*;

class Player {
    final String name;
    Player(String name) { this.name = name; }
}
class Team {                                     // aggregation: a team groups players it didn't create
    final String name;
    final List<Player> players = new ArrayList<>();
    Team(String name) { this.name = name; }
    void join(Player p) { players.add(p); }
}
public class Main {
    public static void main(String[] args) {
        Player meena = new Player("Meena");      // the player exists first
        Team red = new Team("Red House");
        red.join(meena);
        System.out.println(red.name + ": " + red.players.size() + " player");
        red = null;                              // the team is disbanded...
        Team blue = new Team("Blue House");
        blue.join(meena);                        // ...the player lives on and joins another
        System.out.println(meena.name + " now plays for " + blue.name);
    }
}
Red House: 1 player
Meena now plays for Blue House

Rule of thumb: if the whole creates the part and nobody else holds it, composition. If the part comes from outside and can be shared, aggregation. When unsure, plain association is never wrong, just less precise.

7. Inheritance, realization and dependency

Relationship Meaning Line Arrowhead Java
Inheritance (generalization) is-a solid hollow triangle at the parent extends
Realization implements an interface dashed hollow triangle at the interface implements
Dependency uses briefly (parameter, local variable, return type) dashed open arrow a parameter

One program with every relationship:

import java.util.*;

interface Payable { double amount(); }
class Customer { final String name; Customer(String n) { name = n; } }
class OrderLine { final String item; OrderLine(String i) { item = i; } }
class Printer { String format(String who, double amt) { return who + " pays Rs " + amt; } }

class Order implements Payable {                                // realization
    private final Customer customer;                            // association: 1 customer
    private final List<OrderLine> lines = new ArrayList<>();    // composition: 1..* lines
    Order(Customer c) { customer = c; }
    void add(String item) { lines.add(new OrderLine(item)); }
    public double amount() { return lines.size() * 50.0; }
    String receipt(Printer p) { return p.format(customer.name, amount()); }   // dependency
}
class ExpressOrder extends Order {                              // inheritance
    ExpressOrder(Customer c) { super(c); }
    public double amount() { return super.amount() + 30; }
}
public class Main {
    public static void main(String[] args) {
        Order o = new ExpressOrder(new Customer("Ravi"));
        o.add("Idli");
        o.add("Chai");
        System.out.println(o.receipt(new Printer()));
    }
}
Ravi pays Rs 130.0
Order ┄┄▷ «interface» Payable        realization  (implements)
Order * ──▶ 1 Customer                association  (a field)
Order 1 ◆── 1..* OrderLine            composition  (creates its own lines)
ExpressOrder ──▷ Order                inheritance  (extends)
Order ┄┄▶ Printer                     dependency   (a parameter)

8. The cheat sheet

Symbol Name Read it as
── association "has a reference to"
──▶ navigable association "knows" (one way)
◇── aggregation "groups (doesn't own)"
◆── composition "owns; parts die with it"
──▷ inheritance "is a" (extends)
┄┄▷ realization "implements"
┄┄▶ dependency "uses for a moment"

From strongest bond to weakest: composition, aggregation, association, dependency.

Common mistakes

Mistake Exact message / symptom Why Fix
this.lines = lines; (the caller's list) A1 lines: [Dosa x2, Vada x1, Coffee x1] Drew composition, coded sharing Create the list inside; return a copy
a.balance = 1_000_000; balance has private access in Account - means private Use a public operation
Triangle drawn at the child no error: a misread diagram The triangle points at the parent Child ──▷ Parent
1..* drawn, empty order allowed IllegalArgumentException: an order needs at least 1 line (after the fix) Multiplicity not enforced Check it in the constructor
Diamond at the wrong end no error: ownership reversed The diamond sits at the whole/owner Order ◆── OrderLine
Every field drawn as both an attribute and a line cluttered diagram Same fact shown twice Show a relationship either as a line or as an attribute

Mini project

Draw a library: a Library owns its Books; a Member can have at most 3 Loans; each Loan links one book to one member and is due in 14 days. Then code it and enforce the multiplicity.

Library 1 ◆──── * Book
Loan * ────▶ 1 Book
Loan 0..3 ────── 1 Member
Library ┄┄▶ Member   (lend() takes a Member parameter)
Solution
import java.time.*;
import java.util.*;

class Book {                                     // Library 1 ◆── * Book
    final String isbn, title;
    Book(String isbn, String title) { this.isbn = isbn; this.title = title; }
}
class Member {                                   // Member 1 ── 0..3 Loan (navigable both ways)
    final String name;
    private final List<Loan> loans = new ArrayList<>();
    Member(String name) { this.name = name; }
    void addLoan(Loan l) {
        if (loans.size() == 3) throw new IllegalStateException(name + " already has 3 books");
        loans.add(l);
    }
    int loanCount() { return loans.size(); }
}
class Loan {                                     // Loan * ──▶ 1 Book, * ──▶ 1 Member
    final Book book; final Member member; final LocalDate due;
    Loan(Book b, Member m, LocalDate today) { book = b; member = m; due = today.plusDays(14); m.addLoan(this); }
}
class Library {
    private final Map<String, Book> books = new LinkedHashMap<>();
    void addBook(String isbn, String title) { books.put(isbn, new Book(isbn, title)); }   // composition: creates them
    Loan lend(String isbn, Member m, LocalDate today) { return new Loan(books.get(isbn), m, today); }  // dependency on Member
}
public class Main {
    public static void main(String[] args) {
        Library lib = new Library();
        for (int i = 1; i <= 4; i++) lib.addBook("ISBN-" + i, "Book " + i);
        Member riya = new Member("Riya");
        LocalDate today = LocalDate.of(2026, 10, 30);
        for (int i = 1; i <= 4; i++) {
            try {
                Loan l = lib.lend("ISBN-" + i, riya, today);
                System.out.println(l.book.title + " due " + l.due + " (" + riya.loanCount() + " on loan)");
            } catch (IllegalStateException e) { System.out.println("Refused: " + e.getMessage()); }
        }
    }
}

Output:

Book 1 due 2026-11-13 (1 on loan)
Book 2 due 2026-11-13 (2 on loan)
Book 3 due 2026-11-13 (3 on loan)
Refused: Riya already has 3 books

The 0..3 on the diagram became the check in addLoan.

Practice

1. Composition or aggregation? (a) a phone and its SIM card; (b) a building and its floors; (c) a playlist and its songs; (d) an order and its order lines.

Answer

(a) Aggregation: the SIM exists before the phone and can move to another phone. (b) Composition. (c) Aggregation: songs exist outside any playlist and can be in many. (d) Composition: lines are created by and belong to one order.

2. Write the UML attribute line for protected static final int MAX = 10;.

Answer

# MAX: int = 10, underlined (static). Constants are often also marked {readOnly}.

3. What do the dashed line with a hollow triangle and the dashed line with an open arrow mean?

Answer

Dashed + hollow triangle: realization (implements). Dashed + open arrow: dependency (uses for a moment, e.g. a parameter).

4. Draw the relationships for: class Car { private final Engine engine = new Engine(); void drive(Road road) { ... } }.

Answer

Car ◆── Engine (composition: created inside, never shared) and Car ┄┄▶ Road (dependency: only a parameter).

Quick quiz

class Car {
    private final Engine engine = new Engine();   // created here, never shared
    void drive(Road road) { ... }
}

Which pair is right?

  • A. Car ◇── Engine, Car ┄┄▶ Road
  • B. Car ◆── Engine, Car ┄┄▶ Road
  • C. Car ──▷ Engine, Car ◆── Road
  • D. Car ┄┄▶ Engine, Car ── Road
Answer

B. The car creates and owns its engine: composition. The road is only a parameter: dependency.

Interview questions

  1. What is UML? Who created it? A standard modelling language for software, unified at Rational Software by Booch, Rumbaugh and Jacobson (1994-1995); an OMG standard since 1997 and ISO since 2005.
  2. What are the three compartments of a class box? Name, attributes, operations.
  3. What do + - # ~ mean? Public, private, protected, package.
  4. How are static and abstract shown? Static: underlined. Abstract: italics (or {abstract}).
  5. Aggregation vs composition? Both are has-a. Composition: the whole owns the part and its lifetime (filled diamond). Aggregation: the whole groups parts that exist independently (hollow diamond).
  6. Association vs dependency? Association is a lasting structural link (a field); dependency is a temporary use (a parameter or local variable).
  7. Inheritance vs realization arrows? Both hollow triangles; inheritance uses a solid line (extends), realization a dashed line (implements).
  8. What is navigability? Which side of an association can reach the other, shown by an open arrowhead.
  9. What does 1..* mean, and where do you write it? At least one; at the far end of the line, next to the class it counts.
  10. How detailed should an interview class diagram be? Classes, key operations, relationships and multiplicities first; fields and types only where they clarify the design.

Glossary

Term Meaning, with an example
UML Unified Modeling Language: the standard drawing language for software designs
OMG Object Management Group: the standards body that maintains UML
ISO International Organization for Standardization: publishes international standards
Structural diagram Shows what exists: class diagrams
Behavioural diagram Shows what happens over time: sequence diagrams (next episode)
Class diagram A diagram of classes, their members and their relationships
Class box A rectangle with three compartments: name, attributes, operations
Compartment One section of the class box
Attribute UML's word for a field. - balance: double
Operation UML's word for a method. + deposit(amt: double): void
Visibility marker + public, - private, # protected, ~ package
Static (notation) Underlined: belongs to the class. count
Abstract (notation) Italics or {abstract}: cannot be instantiated / has no body
Stereotype A «word» marking a special kind of element. «interface»
Guillemets The « » brackets around a stereotype
Interface notation A box with «interface», usually only operations
Association A lasting link between classes, usually a field; a solid line
Navigability Which side knows the other; an open arrowhead
Multiplicity How many objects at one end: 1, 0..1, *, 1..*
Aggregation A whole groups parts it doesn't own; hollow diamond ◇
Composition A whole owns parts that die with it; filled diamond ◆
Inheritance / generalization is-a (extends); solid line, hollow triangle at the parent
Realization implements an interface; dashed line, hollow triangle
Dependency uses for a moment (a parameter); dashed line, open arrow
List.copyOf Returns an unmodifiable copy of a list
Defensive copy Copying data in or out so outsiders can't change your object's state (episode 6)

Summary

  • UML is the blueprint language for code (OMG 1997, ISO 2005, UML 2.5.1).
  • Class box: name, attributes, operations; + - # ~; static underlined; abstract italic; «stereotypes».
  • Association (solid line) with navigability (arrow) and multiplicity (1, 0..1, *, 1..*).
  • Composition ◆ owns; aggregation ◇ groups.
  • Inheritance solid ▷, realization dashed ▷, dependency dashed →.
  • Every symbol maps to code; enforce multiplicities in constructors.

Next episode: UML 2: sequence, use-case, activity and state diagrams.