In Software Design Principles we contrasted function-oriented and object-oriented design, and in Modularity, Coupling & Cohesion we learned how to judge a split into modules. To communicate such a design, engineers need a shared drawing language. For object-oriented systems that language is UML.
The Unified Modeling Language (UML) is a standard, general-purpose visual modelling language for specifying, visualising, constructing and documenting the artifacts of a software system.
UML is a notation, not a process. It tells you how to draw a class or a message; it does not tell you in which order to do the work. You can use it with Waterfall, Spiral or Scrum.
A Short History
In the early 1990s there were dozens of competing object-oriented notations. The three most popular were by Grady Booch (Booch method), James Rumbaugh (OMT) and Ivar Jacobson (OOSE, which introduced use cases).
Working together at Rational Software in the mid-1990s, the "three amigos" merged their ideas into UML. The Object Management Group (OMG) adopted UML 1.1 as a standard in 1997.
UML 2.0 (2005) was a major revision that added several new diagram types.
The current formal version is UML 2.5.1 (published by OMG in December 2017). UML 2.4.1 was also published as the international standard ISO/IEC 19505.
The 14 UML Diagram Types
UML 2.5.1 defines 14 diagram types, split into two families:
Structure diagrams show the static parts of the system: what exists and how it is connected.
Behaviour diagrams show the dynamic side: what happens over time. A sub-family, interaction diagrams, focuses on messages exchanged between objects.
UML Diagram
┌───────────────┴───────────────┐
Structure (7) Behaviour (7)
├─ Class ├─ Use Case
├─ Object ├─ Activity
├─ Package ├─ State Machine
├─ Component └─ Interaction (4)
├─ Composite Structure ├─ Sequence
├─ Deployment ├─ Communication
└─ Profile ├─ Timing
└─ Interaction Overview| Diagram | Family | Answers the question |
|---|---|---|
| Class | Structure | What classes exist, with what attributes, operations and relationships? |
| Object | Structure | What does a snapshot of actual objects look like at one moment? |
| Package | Structure | How are model elements grouped, and which group depends on which? |
| Component | Structure | Which replaceable parts make up the system, and through which interfaces do they connect? |
| Composite structure | Structure | What is the internal structure of a class or component (its parts and ports)? |
| Deployment | Structure | On which hardware/execution nodes do the software artifacts run? |
| Profile | Structure | How is UML extended with stereotypes for a specific domain or platform? |
| Use case | Behaviour | Who uses the system, and for what goals? |
| Activity | Behaviour | What is the flow of steps in a process or algorithm? |
| State machine | Behaviour | Which states can an object be in, and which events move it between them? |
| Sequence | Interaction | Which messages are exchanged, in what time order? |
| Communication | Interaction | Which objects are linked, and which numbered messages pass along the links? |
| Timing | Interaction | How do states or values change along a precise time axis? |
| Interaction overview | Interaction | How do several interactions combine in a larger flow (activity-style)? |
Two older names still appear in many syllabi: the communication diagram was called the collaboration diagram in UML 1.x, and the state machine diagram is often called a statechart. In exams and practice, the five you must know well are: class, use case, sequence, activity and state machine. We cover those in detail, then the rest briefly.
Class Diagram
The most used UML diagram. A class is a box with three compartments: name, attributes, operations.
┌──────────────────────────────────┐
│ Student │ ← class name
├──────────────────────────────────┤
│ - rollNo : String │ ← attributes
│ - name : String │
│ - cgpa : float = 0.0 │
│ # branch : String │
├──────────────────────────────────┤
│ + enroll(c : Course) : void │ ← operations
│ + getCgpa() : float │
│ - recalculate() : void │
└──────────────────────────────────┘Visibility markers
| Symbol | Visibility | Accessible from |
|---|---|---|
+ | public | Anywhere |
- | private | Only inside the class |
# | protected | The class and its subclasses |
~ | package | Classes in the same package |
Attribute syntax: visibility name : Type [multiplicity] = default. Operation syntax: visibility name(param : Type) : ReturnType. Static members are underlined in a real diagram, and abstract classes and operations are written in italics (or marked {abstract}).
Relationships between classes
| Relationship | Notation | Meaning | Example |
|---|---|---|---|
| Association | Solid line (optionally with an arrowhead for navigability) | Objects of the two classes are linked | Student — Course |
| Aggregation | Solid line with a hollow diamond at the whole | Weak "has-a"; part can exist without the whole and can be shared | Department ◇— Professor |
| Composition | Solid line with a filled diamond at the whole | Strong "owns"; part belongs to one whole and is deleted with it | Building ◆— Room |
| Generalization (inheritance) | Solid line with a hollow triangle at the parent | "is-a" | UGStudent —▷ Student |
| Realization | Dashed line with a hollow triangle at the interface | A class implements an interface | CardPayment - - ▷ «interface» Payment |
| Dependency | Dashed line with an open arrowhead | "uses" temporarily (parameter, local variable); a change in the target may affect the source | ReportPrinter - - > Printer |
From weakest to strongest coupling between the two classes: dependency → association → aggregation → composition. (Generalization and realization are a different kind of relationship: type relationships, not object links.)
Multiplicity
Written at each end of an association to say how many objects may take part.
| Multiplicity | Meaning |
|---|---|
1 | Exactly one |
0..1 | Zero or one (optional) |
* or 0..* | Zero or more |
1..* | One or more |
2..5 | Between 2 and 5 |
Worked example: a college system
┌──────────┐
│ Person │ {abstract}
└────▲─────┘
┌────────┴────────┐
┌────┴────┐ ┌─────┴─────┐
│ Student │ │ Professor │
└────┬────┘ └─────┬─────┘
│ * │ 1..*
│ enrolls in │ belongs to
│ * │ 1
┌────┴────┐ * ◇────┴──────┐
│ Course │───────│ Department│
└─────────┘ └───────────┘Read it like sentences:
Student and Professor are Persons (generalization; Person is abstract).
A Student enrols in zero or more Courses; a Course has zero or more Students (many-to-many association).
A Professor belongs to exactly one Department; a Department has one or more Professors.
A Department aggregates Courses (hollow diamond on the Department side).
Aggregation vs composition in code
The difference is about lifetime and ownership, which shows up clearly in code:
class Professor:
def __init__(self, name):
self.name = name
class Department: # aggregation: professors exist independently
def __init__(self, name):
self.name = name
self.professors = []
def add(self, prof):
self.professors.append(prof)
class Room:
def __init__(self, number):
self.number = number
class Building: # composition: rooms are created and owned here
def __init__(self, name, n_rooms):
self.name = name
self.rooms = [Room(f"{name[0]}-{i}") for i in range(1, n_rooms + 1)]
rao = Professor("Prof. Rao")
cse = Department("CSE")
cse.add(rao)
del cse # department closed...
print(rao.name, "still exists") # ...the professor is still there
block = Building("Academic", 3)
print([r.number for r in block.rooms])Output:
Prof. Rao still exists
['A-1', 'A-2', 'A-3']The professor was created outside the department and survives its deletion: aggregation. The rooms are created inside the building and nobody else holds them, so they go when the building goes: composition.
Object Diagram
A snapshot of specific objects (instances) and links at one moment. Names are written objectName : ClassName and underlined; attributes show actual values.
┌─────────────────────┐ ┌──────────────────────┐
│ aman : Student │────────│ dbms : Course │
├─────────────────────┤ ├──────────────────────┤
│ rollNo = "21CS042" │ │ code = "CS501" │
│ cgpa = 8.4 │ │ credits = 4 │
└─────────────────────┘ └──────────────────────┘Object diagrams are useful for checking a class diagram against a concrete example.
Use Case Diagram
Captures functional requirements from the user's point of view. It connects naturally to the Requirements Engineering chapter.
Actor (stick figure): a role played by a person or external system that interacts with our system. "Student", "Payment Gateway".
Use case (oval): a goal the actor achieves, named verb-first. "Pay Fees", "Register for Course".
System boundary (rectangle): what is inside our system.
Association (line): actor participates in the use case.
┌────────────── Online Fee System ──────────────┐
│ │
Student ──┼── ( Pay Fees ) - - «include» - - > ( Login ) │
O │ ▲ ╲ │
/|\ │ ¦ ╲______________________________┼── Payment Gateway
/ \ │ ¦ «extend» │ (external system
│ ¦ │ actor)
│ ( Apply Late Fine ) │
│ │
Accountant ─┼── ( Generate Fee Report ) │
│ │
└───────────────────────────────────────────────┘include vs extend
| Aspect | «include» | «extend» |
|---|---|---|
| Meaning | The base use case always uses the included behaviour | The extending behaviour is added to the base only under a condition |
| Arrow direction | From base → included use case | From extending use case → base |
| Base complete without it? | No | Yes |
| Example | Pay Fees «include» Login | Apply Late Fine «extend» Pay Fees (only if paid after the due date) |
Actors and use cases can also have generalization (for example, "Hostel Student" is a kind of "Student").
Sequence Diagram
Shows objects as lifelines (a box with a dashed vertical line) and the messages between them in time order from top to bottom. Thin rectangles on a lifeline are activations (the object is busy executing).
:Student :FeePage :FeeService :PaymentGateway
│ │ │ │
│ pay(amount) │ │ │
│─────────────▶│ │ │
│ │ createOrder() │ │
│ │───────────────▶│ │
│ │ │ charge(card, amt) │
│ │ │──────────────────▶│
│ │ │ status │
│ │ │◀- - - - - - - - - │
│ │ receipt │ │
│ │◀- - - - - - - -│ │
│ show receipt│ │ │
│◀- - - - - - -│ │ │| Message | Notation | Meaning |
|---|---|---|
| Synchronous | Solid line, filled arrowhead | Caller waits for the reply |
| Asynchronous | Solid line, open (stick) arrowhead | Caller continues without waiting |
| Reply / return | Dashed line, open arrowhead | Returns control or a value |
| Create | Dashed line to the head of a new lifeline | Object is created at that point |
| Destroy | An X at the end of a lifeline | Object is destroyed |
Branches and loops are drawn as combined fragments: a labelled box around a group of messages. The most common operators are alt (if/else), opt (if, no else), loop (repetition), par (parallel) and ref (reference to another diagram).
Communication Diagram
Shows the same information as a sequence diagram, but laid out as a graph of linked objects. Order is shown by numbering the messages. Nested decimal numbers show which message was sent while handling which: 1 is the first message, 1.1 is sent by the receiver of message 1 while handling it, 1.1.1 is sent while handling 1.1, and 2 would be the next top-level message.
:Student ──1: pay(amount)──▶ :FeePage ──1.1: createOrder()──▶ :FeeService
│
1.1.1: charge(card, amt)
▼
:PaymentGatewayUse a sequence diagram when timing order matters most; a communication diagram when the links between objects matter most.
Activity Diagram
A flowchart with extra power: it supports parallel flows and swimlanes (partitions showing who does each step). Ideal for business processes and complex algorithms.
| Element | Symbol |
|---|---|
| Initial node | Filled black circle |
| Action | Rounded rectangle |
| Decision / merge | Diamond (guards in square brackets on outgoing edges) |
| Fork / join | Thick black bar (split into / synchronise parallel flows) |
| Activity final | Circle with a filled circle inside (bull's-eye) |
| Flow final | Circle with an X (ends just that flow) |
●
│
( Fill admission form )
│
◇ ◀───────────────────────────────────────────────┐ ← merge
│ │
◇───[documents incomplete]──▶ ( Request documents ) ┘ ← decision
│[complete]
━━━━━┷━━━━━ ← fork
│ │
( Verify marks ) ( Collect fee )
│ │
━━━━━┯━━━━━ ← join (wait for both)
│
( Issue ID card )
│
◉If the documents are incomplete, the flow goes back to the merge node and the check is repeated, so the fork is reached only when the documents are complete. A merge node (also a diamond) brings alternative paths back together; a join bar waits for parallel paths.
State Machine Diagram
Models the life of one object: the states it can be in and the transitions triggered by events. A transition label has the form event [guard] / action.
●──▶ [ Created ] ──submit──▶ [ Submitted ] ──approve [fee paid] / sendMail──▶ [ Approved ]
│ │
reject cancel
▼ ▼
[ Rejected ] ───────────────▶ ◉ ◀────────── [ Cancelled ]Read the long transition as: "when the approve event occurs, if the fee is paid, perform sendMail and move to Approved". Use state machines for objects with interesting lifecycles: orders, tickets, bank accounts, TCP connections.
Remaining Diagrams in Brief
Package diagram: folders (tabbed rectangles) grouping classes, with dependency arrows between packages. Good for showing layered architecture.
Component diagram: components with provided interfaces (lollipop ○) and required interfaces (socket ◡). Shows how replaceable parts plug together.
Deployment diagram: nodes (3-D boxes) such as "Web Server" or "Android Phone", with the artifacts (JAR, executable, database) deployed on them and the communication paths between nodes.
Composite structure diagram: the internal parts and ports of one class or component.
Timing diagram: state of one or more lifelines plotted against a time axis; common in embedded and real-time systems.
Interaction overview diagram: an activity diagram whose nodes are interactions (small sequence diagrams or references to them).
Profile diagram: defines custom stereotypes such as «Entity» or «Controller» to adapt UML to a domain.
Common Mistakes
Putting the diamond on the wrong end. The diamond goes on the whole (Department, Building), not on the part.
Reversing include/extend arrows. Include points from base to included; extend points from the extension to the base.
Drawing use cases as internal functions. "Validate database connection" is not a user goal. Use cases describe what an actor wants to achieve.
Turning a use case diagram into a flowchart. Use case diagrams have no ordering; use an activity diagram for steps.
Using composition for shared parts. If the part can belong to several wholes or outlive the whole, it is aggregation or plain association.
Saying UML is a methodology. It is a language/notation; processes like RUP or Scrum decide when to use it.
Interview and Exam Questions
Q1. How many diagram types does UML 2.5.1 define, and how are they classified?
14: 7 structure diagrams (class, object, package, component, composite structure, deployment, profile) and 7 behaviour diagrams (use case, activity, state machine, plus 4 interaction diagrams: sequence, communication, timing, interaction overview).
Q2. Differentiate aggregation and composition.
Both are whole-part associations. In aggregation (hollow diamond) the part can exist independently and may be shared. In composition (filled diamond) the part belongs to exactly one whole at a time and its lifetime is bound to the whole: deleting the whole deletes the parts.
Q3. Which diagrams are interaction diagrams? What is the difference between sequence and communication diagrams?
Sequence, communication, timing and interaction overview. A sequence diagram emphasises time order (vertical axis); a communication diagram emphasises the links between objects and shows order by message numbers.
Q4. In a class diagram, what do +, -, # and ~ mean?
Public, private, protected and package visibility respectively.
Q5. "ATM Withdraw Cash" always requires "Authenticate PIN", and "Print Receipt" happens only if the user asks. Model these.
Withdraw Cash «include» Authenticate PIN (arrow from Withdraw Cash to Authenticate PIN). Print Receipt «extend» Withdraw Cash (arrow from Print Receipt to Withdraw Cash), with the condition "user requests receipt".
Q6. Which UML diagram would you use to show that the order service runs in a Docker container on an AWS server and talks to a PostgreSQL node?
A deployment diagram: nodes for the server/container and database, artifacts deployed on them, and communication paths between nodes.
Summary
UML is the OMG's standard visual language for object-oriented systems; the current version is 2.5.1. It is a notation, not a process.
14 diagrams: 7 structure (class, object, package, component, composite structure, deployment, profile) and 7 behaviour (use case, activity, state machine, sequence, communication, timing, interaction overview).
Class diagrams show attributes, operations, visibility, multiplicity and relationships: association, aggregation (◇), composition (◆), generalization, realization and dependency.
Use case diagrams show actors and goals; «include» is mandatory, «extend» is conditional.
Sequence diagrams show messages in time order; activity diagrams show workflows with forks and swimlanes; state machines show an object's lifecycle.
Next, Data Flow Diagrams covers the main notation of function-oriented (structured) analysis.