Class diagrams
Read and draw UML at interview speed. Class boxes, every relationship arrow with multiplicities and its code, plus sequence and state diagrams for the flows that matter.
On this page
The problem: explaining a design in words
In a machine-coding round you have 45 minutes and an interviewer who cannot read your mind. Describing a parking lot out loud ("so the lot has floors, and each floor has spots, and the ticket refers to a spot, and a car is a vehicle, and…") loses them by the third clause. Writing all the code first means they only see your structure when it is too late to change.
A sketch with a shared notation fixes both: the interviewer sees every class and how they connect in one glance, and can say "why does the ticket own the spot?" before you have written a line. That notation is UML (the Unified Modeling Language), and in practice you need about a dozen of its symbols.
The idea: boxes for classes, lines for relationships
A class diagram draws each class as a box with three compartments: the name, the fields, the methods. Symbols in front of each member give its visibility: + public, - private, # protected, ~ package-private.
A class box: name, fields, methods
- A UML class diagram is the standard way to sketch classes. Each box has three parts: the name, the fields, and the methods. A plus means public, a minus private, and # means protected.
A few more conventions you will meet:
| Notation | Meaning |
|---|---|
«interface» above the name | An interface |
| Italic name or method | Abstract class or abstract method |
| Underlined member | static |
name: Type / method(arg: Type): Return | Types come after a colon |
Relationships: every arrow, what it means, how it looks in code
This is the part interviewers check. Learn the six lines and you can read any class diagram.
The relationship lines, one kind per step
- Arrows show how classes relate. A solid line with a hollow triangle means inheritance: “is a”. A dashed line with a hollow triangle means a class implements an interface: “can do”.
- A plain line is an association: the classes know about each other for a long time. Numbers at the ends are the multiplicity: one teacher has zero or more students.
- Diamonds mean “has parts”. A filled diamond is composition: the parts can’t live without the whole. Knock down a House and its Rooms are gone. A hollow diamond is aggregation: a Team has Players, but players outlive the team.
- A dashed arrow is a dependency: a short-term “uses”. A Driver uses a Map while planning one trip, perhaps as a method parameter, but doesn’t keep it.
| Relationship | Line | Head | Reads as | Typical code |
|---|---|---|---|---|
| Inheritance (generalisation) | Solid | Hollow triangle at the parent | "is a" | class Car extends Vehicle |
| Realisation | Dashed | Hollow triangle at the interface | "can do" | class Duck implements Swimmable |
| Association | Solid | None, or an open arrow showing who knows whom | "knows a", long-term | A field: List<Student> students |
| Aggregation | Solid | Hollow diamond at the whole | "has a", parts live on | A field holding objects made elsewhere |
| Composition | Solid | Filled diamond at the whole | "owns", parts die with it | A field holding objects it creates and never shares |
| Dependency | Dashed | Open arrow at the thing used | "uses", short-term | A parameter, a local variable, a static call |
The diamond always sits on the whole (the owner); the triangle always points at the parent (the more general type).
The same six relationships in code:
import java.util.ArrayList;
import java.util.List;
// Inheritance: Car is a Vehicle
class Vehicle { }
class Car extends Vehicle { }
// Realisation: Duck can swim
interface Swimmable { void swim(); }
class Duck implements Swimmable { public void swim() { System.out.println("paddle"); } }
// Association, 1 to 0..*: a teacher knows its students long-term
class Student { }
class Teacher { private final List<Student> students = new ArrayList<>(); }
// Composition, 1 to 1..*: the house creates its rooms and never hands them out
class Room { }
class House {
private final List<Room> rooms = new ArrayList<>();
House(int roomCount) { for (int i = 0; i < roomCount; i++) rooms.add(new Room()); }
}
// Aggregation, 0..1 to 0..*: players are created elsewhere and outlive the team
class Player { }
class Team {
private final List<Player> players = new ArrayList<>();
void sign(Player p) { players.add(p); }
void release(Player p) { players.remove(p); }
}
// Dependency: the driver uses a map only during one call
class RoadMap { List<String> route(String a, String b) { return List.of(a, b); } }
class Driver { List<String> plan(RoadMap map) { return map.route("home", "work"); } }# Inheritance: Car is a Vehicle
class Vehicle: ...
class Car(Vehicle): ...
# Realisation: Duck can swim (Python uses an ABC or Protocol as the interface)
from abc import ABC, abstractmethod
class Swimmable(ABC):
@abstractmethod
def swim(self) -> None: ...
class Duck(Swimmable):
def swim(self) -> None:
print("paddle")
# Association, 1 to 0..*: a teacher knows its students long-term
class Student: ...
class Teacher:
def __init__(self):
self.students: list[Student] = []
# Composition, 1 to 1..*: the house creates its rooms and never hands them out
class Room: ...
class House:
def __init__(self, room_count: int):
self._rooms = [Room() for _ in range(room_count)]
# Aggregation, 0..1 to 0..*: players are created elsewhere and outlive the team
class Player: ...
class Team:
def __init__(self):
self.players: list[Player] = []
def sign(self, p: Player) -> None:
self.players.append(p)
def release(self, p: Player) -> None:
self.players.remove(p)
# Dependency: the driver uses a map only during one call
class RoadMap:
def route(self, a: str, b: str) -> list[str]:
return [a, b]
class Driver:
def plan(self, road_map: RoadMap) -> list[str]:
return road_map.route("home", "work")Notice that association, aggregation and composition all look the same in code: a field. The difference is who creates the parts and whether they are shared, which is exactly why the diagram is useful: it records a decision the code alone does not show.
Multiplicity
Multiplicity is the number written at each end of a line: how many objects at that end relate to one object at the other end.
| Written | Means | Example |
|---|---|---|
1 | Exactly one | A Loan is for exactly one Book |
0..1 | Zero or one (optional) | A ParkingSpot holds 0..1 Vehicle |
* or 0..* | Any number, including none | A Teacher has 0..* Students |
1..* | At least one | A House has 1..* Rooms |
0..5 | A specific range | A Member has at most 5 active Loans |
Read it from the far end: on Member 1 ─── 0..5 Loan, the 0..5 sits next to Loan and says "one member has zero to five loans"; the 1 next to Member says "each loan belongs to exactly one member". Multiplicities are where business rules hide, so say them out loud: "0..5 because members may borrow at most five books" shows the interviewer you read the requirements.
A small library design in one picture
- Put together, a small diagram explains a whole design at a glance. Here’s a library: it holds a collection of books (a hollow diamond, because books can outlive the library), and members borrow books through loans. In interviews, draw only the classes and arrows that help explain your idea.
Sequence diagrams: who calls whom, in what order
A class diagram is static: it shows structure, not behaviour. When the hard part of a design is the order of calls (pay before saving, lock before checking), draw a sequence diagram. Each participant gets a box at the top and a dashed lifeline running down; time flows downwards; arrows are messages.
Placing an order: call, reply, and the order that matters
| Element | Drawn as | Means |
|---|---|---|
| Lifeline | Box with a dashed line down | One object (or service) taking part |
| Activation bar | Thin rectangle on a lifeline | That object is busy handling a call |
| Synchronous call | Solid line, filled arrowhead | Caller waits for the answer |
| Asynchronous message | Solid line, open arrowhead | Caller does not wait (an event, a queue message) |
| Return | Dashed line, open arrowhead | The reply; often omitted when obvious |
| Fragment | A labelled frame: alt, opt, loop, par | If/else, optional step, loop, parallel |
In an interview, one sequence diagram for the trickiest flow (booking a seat, paying for a parking ticket) is worth more than five for the easy ones. Add an alt frame for the failure branch: "if the charge fails, the order is not saved and the seat hold is released".
State diagrams: the life of one object
When an object moves through stages (an order, a ticket, an elevator, a vending machine), draw a state diagram: rounded boxes for states, arrows for transitions, each labelled event [guard] / action. The guard in brackets is a condition that must be true for the transition to happen; the action after the slash is what runs when it does. A filled black circle marks the initial state; a circled dot (bullseye) marks a final state.
An order's states, and an event that is not allowed
The diagram translates directly into code: an enum of states plus a table of legal transitions. Anything not in the table is refused, which is the point.
import java.util.EnumMap;
import java.util.Map;
enum OrderState { CREATED, PAID, SHIPPED, DELIVERED, CANCELLED }
enum OrderEvent { PAY, SHIP, DELIVER, CANCEL }
public class Order {
private static final Map<OrderState, Map<OrderEvent, OrderState>> NEXT = new EnumMap<>(OrderState.class);
static {
NEXT.put(OrderState.CREATED, Map.of(OrderEvent.PAY, OrderState.PAID, OrderEvent.CANCEL, OrderState.CANCELLED));
NEXT.put(OrderState.PAID, Map.of(OrderEvent.SHIP, OrderState.SHIPPED, OrderEvent.CANCEL, OrderState.CANCELLED));
NEXT.put(OrderState.SHIPPED, Map.of(OrderEvent.DELIVER, OrderState.DELIVERED));
NEXT.put(OrderState.DELIVERED, Map.of()); // final states: no way out
NEXT.put(OrderState.CANCELLED, Map.of());
}
private OrderState state = OrderState.CREATED; // the initial state
public synchronized void handle(OrderEvent event) {
OrderState to = NEXT.get(state).get(event);
if (to == null) throw new IllegalStateException(state + " + " + event + " is not allowed");
if (state == OrderState.PAID && to == OrderState.CANCELLED) System.out.println("refund issued"); // the action
state = to;
}
public OrderState state() { return state; }
public static void main(String[] args) {
Order o = new Order();
o.handle(OrderEvent.PAY);
o.handle(OrderEvent.CANCEL); // prints: refund issued
System.out.println(o.state()); // CANCELLED
try {
o.handle(OrderEvent.SHIP);
} catch (IllegalStateException e) {
System.out.println(e.getMessage()); // CANCELLED + SHIP is not allowed
}
}
}import threading
from enum import Enum, auto
class OrderState(Enum):
CREATED = auto()
PAID = auto()
SHIPPED = auto()
DELIVERED = auto()
CANCELLED = auto()
class OrderEvent(Enum):
PAY = auto()
SHIP = auto()
DELIVER = auto()
CANCEL = auto()
S, E = OrderState, OrderEvent
NEXT = {
S.CREATED: {E.PAY: S.PAID, E.CANCEL: S.CANCELLED},
S.PAID: {E.SHIP: S.SHIPPED, E.CANCEL: S.CANCELLED},
S.SHIPPED: {E.DELIVER: S.DELIVERED},
S.DELIVERED: {}, # final states: no way out
S.CANCELLED: {},
}
class Order:
def __init__(self):
self.state = S.CREATED # the initial state
self._lock = threading.Lock()
def handle(self, event: OrderEvent) -> None:
with self._lock:
to = NEXT[self.state].get(event)
if to is None:
raise RuntimeError(f"{self.state.name} + {event.name} is not allowed")
if self.state is S.PAID and to is S.CANCELLED:
print("refund issued") # the action
self.state = to
if __name__ == "__main__":
o = Order()
o.handle(E.PAY)
o.handle(E.CANCEL) # prints: refund issued
print(o.state.name) # CANCELLED
try:
o.handle(E.SHIP)
except RuntimeError as e:
print(e) # CANCELLED + SHIP is not allowedWhen each state needs a lot of its own behaviour (a vending machine that reacts to coins, buttons and refills differently in each state), move from a table to one class per state: the State pattern.
Which diagram, when
| Diagram | Shows | Good at | Weak at | Use when |
|---|---|---|---|---|
| Class | Types and their relationships | Structure at a glance, ownership, multiplicities | Order of events, timing | Always, first, in every LLD round |
| Sequence | Calls between objects over time | Ordering, who waits for whom, failure branches | Many participants or branches (it sprawls) | One or two critical flows |
| State | Stages of one object and legal moves | Forbidden transitions, lifecycle rules | Interactions between objects | Orders, tickets, elevators, vending machines |
When not to draw
- Not every class. Draw what you will discuss. Utility classes, DTOs and exceptions rarely belong.
- Not to UML-lawyer precision. Interviewers care that "Ticket references Spot, 1 to 0..1" is right, not whether your arrowhead is open or filled.
- Not as a substitute for code when the round is machine coding: sketch for five minutes, then build. The diagram is a plan, not a deliverable.
In the interview
Requirements: a lot has several floors; each floor has many spots of sizes small, medium and large; cars, bikes and trucks park; a ticket records one vehicle in one spot with an entry time; pricing rules vary by lot. List the classes and every relationship with its symbol and multiplicities.
Compare with our answer
ParkingLot ◆──── 1..* ParkingFloor composition: floors don't exist without the lot
ParkingFloor ◆── 1..* ParkingSpot composition
ParkingSpot ──── 0..1 Vehicle association: a spot holds at most one vehicle
Car, Bike, Truck ──▷ Vehicle inheritance (abstract Vehicle, italic)
Ticket ──── 1 Vehicle, Ticket ──── 1 ParkingSpot association; entryTime field
ParkingLot ──── 1 PricingStrategy association (or aggregation); interface
HourlyPricing, FlatPricing ┄┄▷ PricingStrategy realisation (dashed, hollow triangle)
ParkingSpot: - size: SpotSize enum SpotSize { SMALL, MEDIUM, LARGE }
A strong answer mentions: composition from lot to floors to spots · 0..1 vehicle per spot · an abstract Vehicle with three subclasses (or a VehicleType enum if they don't behave differently) · Ticket associated with exactly one vehicle and one spot · PricingStrategy as an interface with realisations · SpotSize as an enum.
The order lifecycle gains returns: a delivered order can be returned within 30 days, which moves it to RETURN_REQUESTED; when the warehouse receives the item, it becomes RETURNED and a refund is issued. How do the state diagram and the transition table change?
Compare with our answer
New states RETURN_REQUESTED and RETURNED (final). New transitions: DELIVERED --requestReturn [within 30 days of delivery]--> RETURN_REQUESTED and RETURN_REQUESTED --receive / refund--> RETURNED. DELIVERED is no longer final. In code, add two enum constants and two table entries; the guard needs the delivery time, so the order records deliveredAt when it enters DELIVERED, and the time check runs in handle before the table lookup is applied (pass the current time in so it can be tested).
A strong answer mentions: two new states, with RETURNED final · a guard written as [within 30 days] on the transition · the refund as an action on the second transition · storing the delivery time to evaluate the guard · that illegal events (returning a cancelled order) are still refused automatically by the table.
- Box: name / fields / methods;
+public,-private,#protected,~package; italic = abstract; underline = static. - Inheritance: solid line, hollow triangle at the parent. Realisation: dashed line, hollow triangle at the interface.
- Association: solid line (field, long-term). Dependency: dashed arrow (parameter or local, short-term).
- Composition ◆ at the owner: parts created by and dying with the whole. Aggregation ◇: parts live on and can be shared.
- Multiplicity at the far end:
1,0..1,*,1..*,0..5; that's where business rules show. - Sequence diagram: lifelines, time downwards; solid arrow = call, dashed = return;
alt/opt/loopframes. - State diagram: states,
event [guard] / actiontransitions; code = enum + transition table, or the State pattern. - Interview: 5–10 classes, multiplicities said out loud, one dynamic diagram for the hardest flow.
1. A Library creates Shelf objects in its constructor and never shares them; when the library object is discarded, so are its shelves. Which line joins them?
Composition puts a filled diamond on the owner. A hollow diamond would mean the shelves exist independently, and a dashed arrow is a short-term dependency, not ownership.
2. On the line Member 1 ──── 0..5 Loan, what does 0..5 mean?
Multiplicity is read from the far end: the number next to Loan says how many loans one member has.
3. OrderService.place(order, gateway) receives a PaymentGateway as a parameter, calls it once, and does not store it. How do you draw that?
Something used only inside a method call is a dependency. A dashed line with a hollow triangle means "implements", and a plain solid line implies a long-lived field.
4. A team argues whether Team to Player should be aggregation or association. What matters most for the design?
The decision that affects the code is lifecycle and sharing, plus how many. Diamonds versus plain lines rarely change behaviour, so don't spend interview time on notation fine print.
5. An interviewer asks how a seat booking avoids charging the card when the seat was taken in the meantime. Which diagram explains your answer best?
The question is about the order of calls and the failure path, which is what sequence diagrams show. A class diagram shows structure but not order.
6. In a vending machine state diagram, a Dispensing state has no arrow for the insertCoin event. What should the code do when a coin arrives while dispensing?
A missing transition means the event is not allowed in that state. Encoding states and legal transitions explicitly is what makes such events refusable rather than corrupting state.
Score 60% or more and the lesson is marked complete.