UML (the Unified Modeling Language) is the shared sketching language of object-oriented design. Two of its diagrams do nearly all the work in practice: the class diagram, which shows the types in a design and how they relate, and the sequence diagram, which shows the messages objects send each other over time. Every pattern lesson in this track draws both, and LLD interviews expect you to sketch them on a whiteboard. This lesson teaches you to read them fluently: every box, line end and arrow in the visualizer means something precise.
Think of it like
A floor plan and a day in the house
An architect's floor plan shows rooms and how they connect: this door joins the kitchen to the hall, that wall is load-bearing. It never changes, whatever happens in the house. That is a class diagram. A sequence diagram is a time-lapse of one morning: who walked from the bedroom to the kitchen, who called whom, and in what order. The plan tells you what can happen; the time-lapse shows what did happen once. You need both to understand the house.
Why UML, and which parts of it
UML 2 defines fourteen diagram types and a thick specification. Almost nobody uses all of it. In design documents, code reviews and interviews, people use a small, stable subset as a sketch, not a blueprint: it lets a reader understand a design in seconds without reading the code. Show the classes and relations that carry the idea and leave out the rest, but draw those correctly, because a hollow diamond and a filled one say different things.
- Class diagrams: boxes for classes and interfaces, six kinds of line between them, multiplicities. Used for LLD rounds, design docs and explaining a pattern.
- Sequence diagrams: lifelines, synchronous calls, returns, object creation, and the
alt/loop/optframes. Used to explain a flow: checkout, login, a retry. - Used less often: state machine diagrams (for objects with a lifecycle), activity diagrams (flowcharts) and component or deployment diagrams (mostly replaced by informal architecture boxes in system design).
Anatomy of a class box
A class box has up to three compartments: the name, the fields (UML calls them attributes) and the methods (operations). Here is CardPayment from the visualizer above:
┌───────────────────────┐
│ «abstract» │ stereotype: what kind of type
│ CardPayment │ name (italic when abstract)
├───────────────────────┤
│ # last4: string │ fields: visibility name: type
├───────────────────────┤
│ + pay(amt): string │ methods: visibility name(params): type
│ # authorize(amt) │
└───────────────────────┘| Notation | Meaning | Example |
|---|---|---|
+ | public: anyone can use it | + pay(amt): string |
- | private: only the class itself | - items |
# | protected: the class and its subclasses | # authorize(amt) |
~ | package (Java's default visibility) | ~ cache |
| «interface» | a pure contract, no state; its methods are abstract | PaymentMethod |
| «abstract» or an italic name | cannot be instantiated; may have abstract methods | CardPayment |
| italic method | abstract method: declared here, implemented in a subclass | + pay(amt) in an interface |
| underlined member | static: belongs to the class, not to each object | + of(code) underlined |
- name: string and - name are both fine. Parameters can be shortened or left out when they add nothing.The six relationships
Lines between boxes are where most reading mistakes happen. There are six kinds, and each line end is drawn at a specific side. The rule that settles direction: the arrowhead or triangle points at the thing being depended on (the parent, the interface, the type that is used), while a diamond sits at the whole, never at the part.
Generalization VisaCard ──────────▷ CardPayment
Realization CardPayment ─ ─ ─ ─▷ PaymentMethod
Association Order ─────────────> PaymentMethod
Dependency Cart ─ ─ ─ ─ ─ ─ ─ > Order
Aggregation Cart ◇────────────── Product
Composition Order ◆───────────── OrderLine| Relationship | Notation | Meaning | Code it usually corresponds to | Lifetime and ownership |
|---|---|---|---|---|
| Generalization (inheritance) | Solid line, hollow triangle at the parent | is-a: the child is a kind of the parent | class VisaCard extends CardPayment | One object: the parent part is inside the child |
| Realization (implements) | Dashed line, hollow triangle at the interface | fulfills a contract | class CardPayment implements PaymentMethod | No runtime link, only a promise of methods |
| Association | Solid line; an open arrowhead shows navigability | has a long-lived reference to | a field: private paidWith: PaymentMethod | Independent lives; neither owns the other |
| Aggregation | Solid line, hollow diamond at the whole | a whole that groups parts it does not own | a collection of references passed in: items: Product[] | Parts exist before the whole and survive it; a part can be shared |
| Composition | Solid line, filled diamond at the whole | a whole made of parts it owns | parts created inside: lines.push(new OrderLine(...)) | Parts die with the whole and belong to exactly one whole |
| Dependency | Dashed line, open arrowhead at the used type | uses, briefly | a parameter, local variable, return type or new inside a method | No stored reference; the link lasts one call |
Aggregation (hollow ◇)
Cart ◇ Product: products are in the catalog before any cart- Delete the cart: the products are still for sale
- The same
Productcan sit in many carts at once - The whole is usually given its parts (
cart.add(book))
Composition (filled ◆)
Order ◆ OrderLine: lines exist only as part of an order- Delete the order: its lines go with it
- A line belongs to exactly one order (multiplicity
1at the whole) - The whole usually creates its parts (
new OrderLine(...)insideOrder)
Association versus dependency is the other common question. If the reference is stored in a field and used across many calls, it is an association. If it only appears as a parameter, a local variable or a return value inside one method, it is a dependency. In the visualizer, Cart.checkout() creates an Order in a local variable and returns it, so Cart ⇢ Order is a dependency, while Order keeps its payment method in the paidWith field, so Order → PaymentMethod is an association.
Multiplicity
A multiplicity near a line end says how many objects can be at that end, for one object at the other end. It can be written at both ends of an association.
| Multiplicity | Reads as | Typical code |
|---|---|---|
1 | exactly one | a required field set in the constructor |
0..1 | zero or one | an optional field (paidWith?: PaymentMethod, or null) |
* or 0..* | any number, possibly none | a list that may be empty (items: Product[]) |
1..* | at least one | a list the class keeps non-empty (an order with no lines is invalid) |
2..4 | a fixed range | a list whose size is checked (players at a table) |
0..* products per cart, 1..* lines per order, 1 payment method per order. On paper you often write both ends (a product can be in 0..* carts; a line belongs to 1 order).Order 1 ◆──────── 1..* OrderLine
for one Order: 1..* OrderLines (at least one line)
for one OrderLine: 1 Order (exactly one owner)Reading the visualizer's class diagram
- 1
Find the abstractions
The visualizer's seven-class shop uses all six relationships; read it like any class diagram, types first. Look for stereotypes and italics.
PaymentMethodis an «interface» (its methodpay(amt)is italic), andCardPaymentis «abstract» (italic name). These are the types other classes should depend on. - 2
Follow the triangles upward
The dashed line with a hollow triangle from
CardPaymenttoPaymentMethodis a realization:CardPayment implements PaymentMethod. The solid line with a hollow triangle fromVisaCardtoCardPaymentis a generalization:VisaCard extends CardPayment. So aVisaCardcan be used anywhere aPaymentMethodis expected. - 3
Read the diamonds from the whole
Orderhas a filled diamond on its side of the line toOrderLine, labeled1..*: an order is composed of one or more lines that it owns.Carthas a hollow diamond on the line toProduct, labeled0..*: a cart groups products it does not own. - 4
Separate fields from passing uses
The solid arrow
Order → PaymentMethod(label1) is an association through thepaidWithfield. The dashed arrowCart ⇢ Orderis a dependency:checkout()creates and returns an order but never stores it. - 5
Check visibility
Fields are private (
-) exceptProduct's public data andCardPayment's protected# last4.# authorize(amt)is protected: onlyCardPaymentand its subclasses can call it, which is exactly whatpay()does. - 6
Press Play and watch the lines light
Each step highlights the relation a message travels:
cart.add(book)lights the aggregation,order.addLine()the dependency,line.cost()the composition, andpaidWith.pay(42)lights the association plus both triangles, because the object behind the interface is aVisaCard.
classDiagram
class PaymentMethod {
<<interface>>
+pay(amt) string
}
class CardPayment {
<<abstract>>
#last4 string
}
Cart "1" o-- "0..*" Product : items
Cart ..> Order : creates
Order "1" *-- "1..*" OrderLine : lines
Order --> "1" PaymentMethod : paidWith
PaymentMethod <|.. CardPayment
CardPayment <|-- VisaCardSequence diagrams
A sequence diagram shows one scenario: which object sends which message to which, in time order. Time flows down; objects are laid out across. The Sequence view in the visualizer is a live sequence diagram that grows by one message per step. Its code is synchronous, so it draws calls, replies, «create» messages and self-calls, but no asynchronous arrows; it also shows field writes as small notes on a lifeline, which is a visualizer extra, not standard UML.
- Lifeline
- A head box naming one participant (
order : Order, an object of classOrder) with a dashed line below it. An object created during the scenario has its head drawn lower, where it is created. - Activation (execution specification)
- The thin rectangle on a lifeline while that object is running a method. A call inside a call stacks a second bar, so nesting depth is visible at a glance.
- Synchronous message
- Solid line, filled arrowhead, labeled
method(args). The caller waits until the callee returns. Ordinary method calls are synchronous. - Asynchronous message
- Solid line, open (stick) arrowhead. The caller continues without waiting: an event, a queue message, a fire-and-forget task.
- Reply (return)
- Dashed line, usually with an open arrowhead, back to the caller, often labeled with the returned value. Often omitted on whiteboards when it adds nothing.
- Create message
- Dashed line with an open arrowhead pointing at the new object's head box, often labeled «create». The lifeline starts there.
- Self-message
- An arrow that leaves a lifeline and loops back into it: an object calling its own method. A nested activation bar shows the inner call.
- Destruction
- An X at the bottom of a lifeline, where the object is destroyed. Mostly used for C++ objects or explicit
close()/dispose().
client cart : Cart
│ │
│ checkout(visa) │
│──────────────────▶█ «create»
│ █- - - - >┌───────────────┐
│ █ │ order : Order │
│ █ └───────┬───────┘
│ █ addLine(...) │
│ █────────────────▶█ «create»
│ █ █- - >┌────────────────┐
│ █ █ │ l1 : OrderLine │
│ █ █ └───────┬────────┘
│ █<- - - - - - - - █ │
│ █ (2nd addLine) │ │
│ order █ │ │
│<- - - - - - - - - █ │ │Real flows branch and repeat. For that UML draws a combined fragment (alt, opt, loop and others): a frame around some messages with an operator in its top-left corner and guards in square brackets. The visualizer does not draw frames (it shows one actual run), so here they are in text:
┌──────┬──────────────────────────────────────┐
│ loop │ [for each product in items] │
├──────┘ │
│ cart ──── addLine(name, price) ───> order │
└─────────────────────────────────────────────┘
┌─────┬───────────────────────────────────────┐
│ alt │ [authorize(amt) is true] │
├─────┘ │
│ card - - - "paid *4242" - - - - > order │
├ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┤
│ [else] │
│ card - - - "declined" - - - - - > order │
└─────────────────────────────────────────────┘| Operator | Meaning | Code shape |
|---|---|---|
alt | choose one of several operands by their guards | if / else if / else, switch |
opt | the content happens only if the guard holds | if with no else |
loop | repeat while the guard holds (loop(1, 3) for bounds) | for, while, retries |
par | operands run in parallel | parallel tasks, fan-out |
break | run this and leave the enclosing fragment | an early return or throw |
ref | insert another sequence diagram by name | a call into a flow drawn elsewhere |
From code to diagram and back
interface Notifier {
send(to: string, msg: string): void;
}
class Library {
private books: Book[] = []; // given to the library
constructor(private notifier: Notifier) {}
addBook(b: Book) { this.books.push(b); }
lend(b: Book, m: Member) { // m: parameter only
b.markLent();
this.notifier.send(m.email, `${b.title} is yours`);
}
}
class Book {
private pages: Page[] = []; // created and owned here
constructor(public title: string) {
this.pages.push(new Page(1));
}
markLent() {}
}
class Page { constructor(public no: number) {} }
class Member { constructor(public email: string) {} }- 1
One box per type
Notifier«interface»,Library,Book,Page,Member. Fields and methods go in the compartments with their visibility. - 2
Fields become structural lines
booksis a list of objects that exist outside the library:Library ◇ Bookwith0..*.pagesare created insideBookand never shared:Book ◆ Pagewith1..*.notifieris a single long-lived reference: an associationLibrary → Notifierwith1. - 3
Parameters become dependencies
Memberappears only as a parameter oflend(): a dependencyLibrary ⇢ Member. Draw it only if it helps the reader. - 4
extends and implements become triangles
Each class that implements
Notifier(anEmailNotifier, say) gets a dashed line with a hollow triangle pointing atNotifier. - 5
Back from diagram to code
Reading the other way, a filled diamond tells you who creates the parts and whose lifetime they follow, a hollow diamond tells you the parts are passed in, and an arrow to an interface tells you to type the field as the interface, not as a concrete class.
┌───────────┐ notifier 1 ┌───────────────┐
│ Library │────────────>│ «interface» │
└───────────┘ │ Notifier │
◇ ┆ └───────────────┘
│ ┆ lend(b, m) △
│ └ ─ ─ ─ ─ > Member ┆
│ 0..* EmailNotifier
┌──────┐ 1 1..* ┌──────┐
│ Book │◆──────────────│ Page │
└──────┘ └──────┘A drawing checklist for interviews
- 1List the nouns of the problem and keep only those with behavior or identity. Those are your classes; the rest are fields.
- 2Draw the boxes with names first. Add only the fields and methods that matter to the discussion;
- itemsbeats ten getters. - 3Mark interfaces and abstract classes, and put parents above children so every triangle points up.
- 4Draw the has-a lines, choose aggregation or composition with the deletion test, and write the multiplicities.
- 5Add dependencies only where they explain something (a factory, a service that receives a parameter).
- 6Walk one use case with a sequence diagram: the main object's lifeline on the left, calls to the right, returns dashed. Put
altorloopframes only around the interesting branch. - 7Narrate as you draw: "
Orderowns its lines, so filled diamond;Cartonly references products, so hollow." The reasoning scores more than the picture.
Common mistakes
- Diamond at the wrong end. The diamond always sits at the whole (
Order ◆── OrderLine), never at the part. - Swapping the diamonds. Filled means owned and destroyed together; hollow means shared and independent. When unsure, a plain association is better than a wrong diamond.
- Triangle pointing down. Generalization and realization point from the child to the parent (
VisaCard ──▷ CardPayment). Readingextendsaloud from the arrow's tail gets it right. - Solid triangle line for an interface.
implementsis dashed;extendsis solid. - Arrowheads on every association. An open arrowhead shows navigability (which side holds the reference). Add it when it matters; do not use filled heads for structure, those belong to sequence diagrams.
- Over-detail. Getters, setters, every parameter type and every dependency turn a diagram into a code listing. Show what supports the design decision.
- Mixing class and object views. A class diagram has classes (
Order); a sequence diagram has objects (order : Order). Two orders are two lifelines but one class box.
Next, see the notation do real work: The Four Pillars of OOP and Composition vs Inheritance use the same views, Interfaces & Abstract Classes explains the two kinds of abstract type behind the triangles, and Strategy and Observer are the first patterns whose diagrams you can now read at a glance.
Implementation
The visualizer's seven classes as a complete program, so each line of the class diagram can be matched to code: Cart aggregates Products it is given, Order creates and owns its OrderLines (composition), Order keeps a PaymentMethod in a field (association), Cart creates an Order in a local variable (dependency), CardPayment implements the PaymentMethod interface and VisaCard extends CardPayment. In C++ the ownership is visible in the types: lines are held by value, products by non-owning pointer. Python has no interface keyword, so PaymentMethod is an abstract base class.
from abc import ABC, abstractmethod
class PaymentMethod(ABC): # the interface: abstract methods only
@abstractmethod
def pay(self, amt: int) -> str: ...
class CardPayment(PaymentMethod): # realization (abstract)
def __init__(self, last4: str) -> None:
self._last4 = last4 # "protected" by convention
def pay(self, amt: int) -> str:
if not self._authorize(amt):
return "declined"
return f"paid *{self._last4}"
@abstractmethod
def _authorize(self, amt: int) -> bool: ...
class VisaCard(CardPayment): # generalization
def _authorize(self, amt: int) -> bool:
return amt <= 500 # card limit
class Product:
def __init__(self, name: str, price: int) -> None:
self.name = name
self.price = price
class OrderLine:
def __init__(self, name: str, price: int) -> None:
self.__name = name
self.__price = price
def cost(self) -> int:
return self.__price
class Order:
def __init__(self, paid_with: PaymentMethod) -> None:
self.__lines: list[OrderLine] = [] # composition
self.__paid_with = paid_with # association
def add_line(self, name: str, price: int) -> None:
self.__lines.append(OrderLine(name, price))
def total(self) -> int:
return sum(line.cost() for line in self.__lines)
def pay(self) -> str:
amount = self.total() # self-call
return self.__paid_with.pay(amount)
class Cart:
def __init__(self) -> None:
self.__items: list[Product] = [] # aggregation
def add(self, p: Product) -> None:
self.__items.append(p)
def checkout(self, pm: PaymentMethod) -> Order: # dependency
order = Order(pm)
for p in self.__items:
order.add_line(p.name, p.price)
return order
book = Product("Book", 30)
pen = Product("Pen", 12)
visa = VisaCard("4242")
cart = Cart()
cart.add(book)
cart.add(pen)
order = cart.checkout(visa)
print(order.total(), order.pay()) # 42 paid *4242Key takeaways
- In practice UML means two diagrams: class diagrams for structure and sequence diagrams for one flow over time. Learn their small common subset well rather than all of UML.
- A class box shows name, fields and methods with visibility (
+public,-private,#protected,~package); «interface», «abstract» and italics mark abstract types, and static members are underlined. - Triangles point at the supertype: solid for extends (generalization), dashed for implements (realization). Diamonds sit at the whole: filled for composition (owned, dies with the whole), hollow for aggregation (shared, outlives it).
- A stored field is an association (solid line); a parameter, local variable or
newinside one method is a dependency (dashed line, open arrowhead). Multiplicities such as1,0..1,0..*and1..*say how many objects sit at each end. - In a sequence diagram time flows down: solid line and filled head for a synchronous call, dashed line for a reply, «create» to start a lifeline, stacked activation bars for nested and self-calls, and
alt/opt/loopframes for branches and repetition.
Common pitfalls
- Putting the diamond at the part's end, or pointing an inheritance triangle at the child. The diamond marks the whole; the triangle marks the parent or interface.
- Using composition for anything stored in a list. If the parts are passed in, shared or outlive the container (
CartandProduct), it is aggregation or a plain association. - Drawing
implementswith a solid line, orextendswith a dashed one. The line style is the only thing that tells them apart. - Drawing every getter, setter and dependency. Over-detailed diagrams hide the design decision; keep the members that matter to the discussion.
Interview tips
- Narrate the notation as you draw it ("
Orderowns its lines, filled diamond, one or more"). Choosing the right relationship and saying why is what the interviewer is checking. - Sketch the class diagram first, then walk the main use case as a sequence diagram. Calling out a self-call, a «create» and an
altfor the failure branch shows you can think in both structure and behavior. - If you are unsure between aggregation and composition, draw a plain association and say what ownership you intend. A correct plain line beats a wrong diamond.
Real-world applications
- Low-level design interviews: parking lots, elevators, libraries and shops are almost always answered with a class diagram plus one or two sequence diagrams.
- Design documents and RFCs: a class diagram of the new types and a sequence diagram of the critical flow, often written in Mermaid or PlantUML and rendered in the wiki.
- Code reviews and onboarding: a quick sequence diagram of a request through controllers, services and repositories explains more than a file list.
- Documenting design patterns: the Gang of Four book describes every pattern with a class diagram (the "structure") and an interaction diagram (the "collaborations").
Test yourself
In a class diagram, a dashed line runs from CardPayment to PaymentMethod and ends in a hollow triangle at PaymentMethod. What does it say?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.