Object-oriented basics · Chapter 5

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.

BeginnerInterview priority: Medium40 min
On this page
  1. The problem: explaining a design in words
  2. The idea: boxes for classes, lines for relationships
  3. Relationships: every arrow, what it means, how it looks in code
  4. Sequence diagrams: who calls whom, in what order
  5. State diagrams: the life of one object
  6. Which diagram, when
  7. When not to draw
  8. In the interview
  9. Quiz

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

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

NotationMeaning
«interface» above the nameAn interface
Italic name or methodAbstract class or abstract method
Underlined memberstatic
name: Type / method(arg: Type): ReturnTypes 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

  1. 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”.
  2. 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.
  3. 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.
  4. 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.
RelationshipLineHeadReads asTypical code
Inheritance (generalisation)SolidHollow triangle at the parent"is a"class Car extends Vehicle
RealisationDashedHollow triangle at the interface"can do"class Duck implements Swimmable
AssociationSolidNone, or an open arrow showing who knows whom"knows a", long-termA field: List<Student> students
AggregationSolidHollow diamond at the whole"has a", parts live onA field holding objects made elsewhere
CompositionSolidFilled diamond at the whole"owns", parts die with itA field holding objects it creates and never shares
DependencyDashedOpen arrow at the thing used"uses", short-termA 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"); } }

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.

WrittenMeansExample
1Exactly oneA Loan is for exactly one Book
0..1Zero or one (optional)A ParkingSpot holds 0..1 Vehicle
* or 0..*Any number, including noneA Teacher has 0..* Students
1..*At least oneA House has 1..* Rooms
0..5A specific rangeA 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

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

ElementDrawn asMeans
LifelineBox with a dashed line downOne object (or service) taking part
Activation barThin rectangle on a lifelineThat object is busy handling a call
Synchronous callSolid line, filled arrowheadCaller waits for the answer
Asynchronous messageSolid line, open arrowheadCaller does not wait (an event, a queue message)
ReturnDashed line, open arrowheadThe reply; often omitted when obvious
FragmentA labelled frame: alt, opt, loop, parIf/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
        }
    }
}

When 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

DiagramShowsGood atWeak atUse when
ClassTypes and their relationshipsStructure at a glance, ownership, multiplicitiesOrder of events, timingAlways, first, in every LLD round
SequenceCalls between objects over timeOrdering, who waits for whom, failure branchesMany participants or branches (it sprawls)One or two critical flows
StateStages of one object and legal movesForbidden transitions, lifecycle rulesInteractions between objectsOrders, 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

Your turn: a parking lot diagram

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.

Your turn: the requirement changes

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.

Class diagrams on one page
  • 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/loop frames.
  • State diagram: states, event [guard] / action transitions; code = enum + transition table, or the State pattern.
  • Interview: 5–10 classes, multiplicities said out loud, one dynamic diagram for the hardest flow.
Interactive labPractise it: draw a toy fire truckOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

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?

2. On the line Member 1 ──── 0..5 Loan, what does 0..5 mean?

3. OrderService.place(order, gateway) receives a PaymentGateway as a parameter, calls it once, and does not store it. How do you draw that?

4. A team argues whether Team to Player should be aggregation or association. What matters most for the design?

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?

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?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.