Chapter 25 of 26

UML Class Diagrams

Before constructing a building, an architect draws a blueprint. The builders, electricians and plumbers all read the same drawing, and everyone understands its symbols. Software teams need the same thing: a way to show the classes of a system and how they relate, before (or instead of) reading thousands of lines of code.

The standard "blueprint language" for object-oriented software is UML, and the diagram you will draw most often is the class diagram. In university exams you are asked to draw class diagrams for a library or banking system; in interviews (especially low-level design rounds) you sketch one on a whiteboard; and every design pattern from the previous chapters is normally described with one.

In this chapter we will learn how to draw a class, how to show visibility, static and abstract members, the six relationships (association, aggregation, composition, generalization, realization and dependency), multiplicity, and how to convert a diagram to Java code and back.


What Is UML?

UML (Unified Modeling Language) is a standard, general-purpose visual language for specifying, visualising, constructing and documenting the design of software systems.

UML grew out of the work of Grady Booch, James Rumbaugh and Ivar Jacobson in the 1990s. It was adopted as a standard by the Object Management Group (OMG) in 1997 and is also published as ISO/IEC 19501 (UML 1.4.2) and ISO/IEC 19505 (UML 2.4.1). The current OMG version is UML 2.5.1.

UML 2 defines 14 diagram types in two groups:

Structure diagrams (static: what the system is)

Behaviour diagrams (dynamic: what the system does)

Class, Object, Component, Composite Structure, Deployment, Package, Profile

Use Case, Activity, State Machine, and the interaction diagrams: Sequence, Communication, Timing, Interaction Overview

A class diagram is a structure diagram. It shows classes, their attributes and operations, and the relationships between them. It does not show the order in which things happen; that is the job of sequence and activity diagrams.


Drawing a Class

A class is a rectangle with up to three compartments:

┌────────────────────────────────────────┐
│                Student                 │  ← 1. name
├────────────────────────────────────────┤
│ - rollNo : int                         │  ← 2. attributes
│ - name : String                        │
│ # cgpa : double = 0.0                  │
│ + collegeName : String {static}        │
├────────────────────────────────────────┤
│ + Student(rollNo : int, name : String) │  ← 3. operations
│ + getName() : String                   │
│ + updateCgpa(newCgpa : double) : void  │
│ ~ validate() : boolean                 │
└────────────────────────────────────────┘

The same class in Java:

public class Student {
    private int rollNo;
    private String name;
    protected double cgpa = 0.0;
    public static String collegeName;

    public Student(int rollNo, String name) { ... }
    public String getName() { ... }
    public void updateCgpa(double newCgpa) { ... }
    boolean validate() { ... }          // package-private
}

Only the name compartment is compulsory. In early analysis you often draw just a box with a name, and add details later.

Attribute and Operation Syntax

UML writes the name first and the type after a colon — the reverse of Java:

Attribute:  visibility name : Type [multiplicity] = defaultValue
            - marks : int[1..*]
            # cgpa : double = 0.0

Operation:  visibility name(parameter : Type, ...) : ReturnType
            + updateCgpa(newCgpa : double) : void
            + getName() : String

Visibility Symbols

Symbol

Visibility

Java keyword

+

Public

public

-

Private

private

#

Protected

protected

~

Package

(no keyword — default access)

These map directly onto the levels from Access Modifiers. A well-encapsulated class (Encapsulation) shows mostly - attributes and + operations.

Static, Abstract, Interfaces and Enums

  • Static members are underlined. Plain text can't underline, so text-based tools write {static} instead (as we did above for collegeName).

  • Abstract classes and operations are written in italics, or marked {abstract}.

  • Interfaces get the stereotype «interface» above the name. Stereotypes are written in guillemets « ».

  • Enumerations get «enumeration» and list their literals in the second compartment.

┌─────────────────────┐   ┌─────────────────────────┐   ┌───────────────┐
│     «interface»     │   │     Shape {abstract}    │   │ «enumeration» │
│       Payable       │   ├─────────────────────────┤   │     Grade     │
├─────────────────────┤   │ # name : String         │   ├───────────────┤
│ + pay(amt : double) │   ├─────────────────────────┤   │ A             │
│     : boolean       │   │ + area() : double       │   │ B             │
└─────────────────────┘   │     {abstract}          │   │ C             │
                          │ + describe() : String   │   └───────────────┘
                          └─────────────────────────┘

Relationships Between Classes

Classes are not islands. UML class diagrams show six main kinds of relationship (plus multiplicity, which decorates association lines), each with its own line and arrowhead.

Association         A ─────────── B     A and B are structurally linked
Directed assoc.     A ──────────▶ B     A knows about B (navigability)
Aggregation         A ◇────────── B     A is a whole, B a part that can live on its own
Composition         A ◆────────── B     A owns B; B cannot exist without A
Generalization      B ──────────▷ A     B is a subclass of A (inheritance)
Realization         B - - - - - ▷ A     B implements interface A
Dependency          A - - - - - > B     A uses B temporarily

Remember: the diamond is always on the whole (container) side, and the triangle always points to the parent / interface.

1. Association

A solid line means objects of one class are connected to objects of another for a long time — usually one holds a reference to the other as a field. A name on the line can describe it ("teaches", "owns"), and role names at the ends describe what each side is to the other.

An arrowhead shows navigability: Customer ──▶ Account means a customer object can reach its accounts (it has a field), but an account doesn't hold a reference back. A line without arrows means navigability is unspecified, or two-way.

Multiplicity on Associations

Numbers at each end of an association say how many objects on that end can be linked to one object on the other end.

Multiplicity

Meaning

1

Exactly one

0..1

Zero or one (optional)

* or 0..*

Zero or more

1..*

One or more

2..5

Between two and five

Reading rule: stand on one class and read the number at the far end.

   Teacher  1 ───────── teaches ───────── 0..* Course

"One teacher teaches zero or more courses" (read 0..* at the Course end) and "each course is taught by exactly one teacher" (read 1 at the Teacher end). In code, a 1-end usually becomes a single field and a *-end becomes a collection: Teacher has a List<Course>, and Course has a Teacher.

This is the same idea as cardinality in ER diagrams, so if you have studied DBMS, the rules will feel familiar.

2. Aggregation (Hollow Diamond)

Aggregation is a special association meaning "whole–part, but the part can exist independently". A department has professors; if the department is closed, the professors still exist and can join another department.

   Department ◇────────── 1..* Professor

3. Composition (Filled Diamond)

Composition is the strong form: the whole owns its parts, a part belongs to at most one whole at a time, and when the whole is destroyed, its parts are destroyed with it. A house and its rooms; an order and its order lines.

   House ◆────────── 1..* Room

Because a part can belong to only one composite, the multiplicity at the diamond end of a composition is always 1 or 0..1. We compared association, aggregation and composition in detail, with code, in Association, Aggregation & Composition; here we only need their symbols.

Feature

Association

Aggregation

Composition

Symbol

Plain line

Hollow diamond ◇ at whole

Filled diamond ◆ at whole

Relationship

"uses / knows"

"has-a" (weak)

"owns / part-of" (strong)

Part's lifetime

Independent

Independent

Tied to the whole

Part shared by several wholes?

Yes

Possible

No

Typical Java code

Field set from outside

Part passed in from outside

Part created inside the whole, never handed out

4. Generalization (Inheritance)

A solid line with a hollow triangle pointing to the superclass. It means "is-a" and corresponds to extends (Inheritance). Several subclasses usually share one triangle, drawn as a tree:

              Vehicle
                 △
        ┌────────┼────────┐
       Car     Bike     Truck

5. Realization (Implementing an Interface)

A dashed line with a hollow triangle pointing to the interface. It corresponds to implements. Some diagrams use the shorter "lollipop" notation: a small circle labelled with the interface name attached to the class.

6. Dependency

A dashed line with an open arrow. It is the weakest relationship: class A uses class B for a short time, typically as a method parameter, a local variable, or a call to a static method, but does not keep a reference to it in a field. If B changes, A might have to change.

Relationship Strength

weakest                                                   strongest
Dependency  →  Association  →  Aggregation  →  Composition
 (uses)         (knows)         (has, shared)   (owns, lifecycle)

Generalization / Realization are a different kind: "is-a" rather than "has-a".

Worked Example: From Diagram to Code

Here is a small banking system. Read it slowly, one line at a time:

┌────────────────────────────┐
│            Bank            │                ┌──────────────────┐
├────────────────────────────┤ 1         1..* │      Branch      │
│ - name : String            │◆───────────────├──────────────────┤
├────────────────────────────┤                │ - ifsc : String  │
│ + addCustomer(c : Customer)│                └──────────────────┘
│     : void                 │
│ + printSummary() : void    │
└─────────────◇──────────────┘
              │
              │
              │ 0..*
┌─────────────┴──────────────┐              ┌───────────────────────────────┐
│          Customer          │              │          «interface»          │
├────────────────────────────┤              │           Notifiable          │
│ - name : String            │┄┄┄┄┄┄┄┄┄┄┄┄┄▷├───────────────────────────────┤
├────────────────────────────┤              │ + sendAlert(message : String) │
│ + addAccount(a : Account)  │              │     : void                    │
│     : void                 │              └───────────────────────────────┘
└─────────────┬──────────────┘
            1 │
              │ owns
              │ 1..*
              ▼
┌────────────────────────────────┐              ┌────────────────────────┐
│       Account {abstract}       │              │   InterestCalculator   │
├────────────────────────────────┤              ├────────────────────────┤
│ - totalAccounts : int {static} │              │ - ratePercent : double │
│ - accountNo : String           │              ├────────────────────────┤
│ # balance : double             │              │ ~ interestFor(amount : │
├────────────────────────────────┤              │     double) : double   │
│ + deposit(amount : double)     │              └────────────────────────┘
│     : void                     │                                      ^
│ + withdraw(amount : double)    │                                      ┆
│     : boolean {abstract}       │                                      ┆
└────────────────△───────────────┘                                      ┆
                 │                                                      ┆
          ┌──────┴──────────────────────────────────┐                   ┆«use»
┌─────────┴──────────────────────┐    ┌─────────────┴───────────────┐   ┆
│         SavingsAccount         │    │        CurrentAccount       │   ┆
├────────────────────────────────┤    ├─────────────────────────────┤   ┆
│ - minBalance : double          │    │ - overdraftLimit : double   │   ┆
├────────────────────────────────┤    ├─────────────────────────────┤   ┆
│ + withdraw(amount : double)    │    │ + withdraw(amount : double) │   ┆
│     : boolean                  │    │     : boolean               │   ┆
│ + addInterest(calc :           │    └─────────────────────────────┘   ┆
│     InterestCalculator) : void │                                      ┆
└──────────────┬─────────────────┘                                      ┆
               ┆                                                        ┆
               └┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘

Reading it:

  • Bank ◆── Branch (1 to 1..*): composition. A bank has one or more branches; a branch belongs to exactly one bank and doesn't exist without it. In code, the bank creates its branches itself.

  • Bank ◇── Customer (0..* customers): aggregation. A customer is created outside and added to the bank; the customer object would still exist if the bank object were discarded.

  • Customer ──▶ Account (1 to 1..*): directed association. A customer holds a list of one or more accounts; an account doesn't point back.

  • Customer ┄▷ Notifiable: realization. Customer implements Notifiable.

  • SavingsAccount, CurrentAccount ──▷ Account: generalization. Account is abstract (its withdraw is abstract), and both subclasses override withdraw.

  • SavingsAccount ┄> InterestCalculator: dependency. It is only a parameter of addInterest(), not a field.

  • totalAccounts is {static} (underlined in a hand-drawn diagram): one counter shared by all accounts.

Now the code that implements this diagram:

import java.util.ArrayList;
import java.util.List;

interface Notifiable {
    void sendAlert(String message);
}

abstract class Account {
    private static int totalAccounts = 0;
    private final String accountNo;
    protected double balance;

    Account(String accountNo, double opening) {
        this.accountNo = accountNo;
        this.balance = opening;
        totalAccounts++;
    }

    public void deposit(double amount) { balance += amount; }

    public abstract boolean withdraw(double amount);

    public String getAccountNo() { return accountNo; }
    public double getBalance() { return balance; }
    public static int getTotalAccounts() { return totalAccounts; }
}

class SavingsAccount extends Account {
    private final double minBalance = 1000;

    SavingsAccount(String no, double opening) { super(no, opening); }

    @Override
    public boolean withdraw(double amount) {
        if (balance - amount < minBalance) return false;
        balance -= amount;
        return true;
    }

    public void addInterest(InterestCalculator calc) {   // dependency: used only as a parameter
        balance += calc.interestFor(balance);
    }
}

class CurrentAccount extends Account {
    private final double overdraftLimit = 5000;

    CurrentAccount(String no, double opening) { super(no, opening); }

    @Override
    public boolean withdraw(double amount) {
        if (balance - amount < -overdraftLimit) return false;
        balance -= amount;
        return true;
    }
}

class InterestCalculator {
    private final double ratePercent;
    InterestCalculator(double ratePercent) { this.ratePercent = ratePercent; }
    double interestFor(double amount) { return amount * ratePercent / 100; }
}

class Customer implements Notifiable {
    private final String name;
    private final List<Account> accounts = new ArrayList<>();   // association, 1..*

    Customer(String name, Account first) {
        this.name = name;
        accounts.add(first);
    }

    public void addAccount(Account a) { accounts.add(a); }
    public List<Account> getAccounts() { return accounts; }
    public String getName() { return name; }

    @Override
    public void sendAlert(String message) {
        System.out.println("Alert to " + name + ": " + message);
    }
}

class Branch {
    private final String ifsc;
    Branch(String ifsc) { this.ifsc = ifsc; }
    public String getIfsc() { return ifsc; }
}

class Bank {
    private final String name;
    private final List<Branch> branches = new ArrayList<>();     // composition: Bank creates and owns them
    private final List<Customer> customers = new ArrayList<>();  // aggregation: customers exist on their own

    Bank(String name, String... ifscCodes) {
        this.name = name;
        for (String code : ifscCodes) {
            branches.add(new Branch(code));
        }
    }

    public void addCustomer(Customer c) { customers.add(c); }

    public void printSummary() {
        System.out.println(name + ": " + branches.size() + " branches, "
                + customers.size() + " customers, "
                + Account.getTotalAccounts() + " accounts");
    }
}

class Main {
    public static void main(String[] args) {
        Bank bank = new Bank("Bharat Bank", "BHRT0000101", "BHRT0000102");

        SavingsAccount s = new SavingsAccount("SB-1", 10000);
        Customer kavya = new Customer("Kavya", s);
        kavya.addAccount(new CurrentAccount("CA-7", 2000));
        bank.addCustomer(kavya);

        s.addInterest(new InterestCalculator(4));
        System.out.println("SB-1 balance: " + s.getBalance());
        System.out.println("Withdraw 9500 from SB-1: " + s.withdraw(9500));
        System.out.println("Withdraw 6000 from CA-7: " + kavya.getAccounts().get(1).withdraw(6000));
        kavya.sendAlert("CA-7 is now overdrawn");
        bank.printSummary();
    }
}

Output:

SB-1 balance: 10400.0
Withdraw 9500 from SB-1: false
Withdraw 6000 from CA-7: true
Alert to Kavya: CA-7 is now overdrawn
Bharat Bank: 2 branches, 1 customers, 2 accounts

Check the mapping yourself:

Diagram element

Java code

«interface» Notifiable

interface Notifiable

Account {abstract}, withdraw {abstract}

abstract class Account, public abstract boolean withdraw(double)

- totalAccounts : int {static}

private static int totalAccounts

# balance : double

protected double balance

Generalization △

extends Account

Realization (dashed △)

implements Notifiable

Composition ◆ Bank–Branch

Bank creates new Branch(code) inside its constructor and keeps them in a private list

Aggregation ◇ Bank–Customer

addCustomer(Customer c) receives an object created elsewhere

Association Customer → Account, 1..*

List<Account> accounts; the constructor requires a first account, so there is always at least one

Dependency ┄> InterestCalculator

Only a method parameter, no field

Notice how multiplicity 1..* was enforced in code: Customer's constructor takes the first Account, so a customer with zero accounts cannot be created. Diagrams carry rules, and good code respects them.


From Code to Diagram

Exams also go the other way: "Draw the class diagram for the following code." Use this checklist:

  1. One box per class/interface/enum. Add «interface» or {abstract} where needed.

  2. For each field: visibility, name, type. Underline (or mark {static}) static fields.

  3. For each method: visibility, name, parameters with types, return type.

  4. extends → solid line + hollow triangle. implements → dashed line + hollow triangle.

  5. A field whose type is another class → association. Is it a whole–part? Does the whole create and solely own it (composition ◆) or receive it from outside (aggregation ◇)?

  6. A collection field (List<X>) → multiplicity * (or 1..* if at least one is guaranteed) at the X end.

  7. A class used only as a parameter, local variable or static call → dependency.

Small exercise: what relationship does this code show?

class Car {
    private final Engine engine = new Engine();   // created inside, never shared
    private Driver driver;                         // set from outside, can change
    void refuel(FuelStation station) { ... }      // only a parameter
}

Answer

Car ◆── 1 Engine (composition: the car creates and owns its engine), Car ── 0..1 Driver (association, or aggregation if you view the driver as a part; the driver exists independently and may be absent), and Car ┄> FuelStation (dependency: used only as a parameter).


Drawing Class Diagrams with Text Tools

In practice, developers often write diagrams as text and let a tool draw them. Two popular tools are PlantUML and Mermaid (Mermaid diagrams render directly in GitHub and many Markdown editors). Here is part of our bank diagram in Mermaid syntax:

classDiagram
    class Notifiable {
        <<interface>>
        +sendAlert(String message) void
    }
    class Account {
        <<abstract>>
        -int totalAccounts$
        -String accountNo
        #double balance
        +deposit(double amount) void
        +withdraw(double amount) boolean*
    }
    Account <|-- SavingsAccount
    Account <|-- CurrentAccount
    Notifiable <|.. Customer
    Bank "1" *-- "1..*" Branch
    Bank o-- "0..*" Customer
    Customer "1" --> "1..*" Account : owns
    SavingsAccount ..> InterestCalculator : uses

In Mermaid, <|-- is inheritance, <|.. realization, *-- composition, o-- aggregation, --> directed association and ..> dependency; a trailing $ marks static and * marks abstract. The symbols are tool-specific, but the concepts are pure UML.


Common Mistakes

  • Diamond on the wrong end. The diamond goes on the whole (Bank, House), not the part.

  • Generalization arrow pointing to the child. The triangle points to the parent: "Car is a Vehicle" → arrow from Car to Vehicle.

  • Solid vs dashed triangles. Solid = extends (generalization); dashed = implements (realization).

  • Using composition when parts are shared. If the same object can belong to two wholes, it is not composition.

  • Writing Java-style types (int marks) instead of UML style (marks : int) in exams.

  • Reading multiplicity from the wrong end. Stand on one class and read the number at the other end.

  • Drawing an association for a mere parameter. If there is no field, it is a dependency.

  • Putting every getter and setter in the diagram. Diagrams are for communication; show what matters.


Interview and Exam Questions

What do +, -, # and ~ mean in a class diagram?

Public, private, protected and package visibility respectively.

How do you show aggregation and composition in UML? What's the difference?

Both use a diamond at the whole's end: hollow ◇ for aggregation, filled ◆ for composition. In aggregation the part can exist independently and may be shared; in composition the part belongs to only one whole and is destroyed with it.

How are generalization and realization drawn?

Generalization (inheritance, extends): a solid line with a hollow triangle pointing to the superclass. Realization (implements): a dashed line with a hollow triangle pointing to the interface.

What is the difference between association and dependency?

Association is a structural, long-lived link, usually a field holding a reference (solid line). Dependency is a temporary "uses" relationship such as a method parameter or local variable (dashed arrow). Association is stronger.

In "Order 1 ◆──── 1..* OrderLine", what does the multiplicity mean?

Each order has one or more order lines, and each order line belongs to exactly one order. Since it is composition, deleting the order deletes its lines.

How are static and abstract members shown?

Static members are underlined (or marked {static} in text). Abstract classes and operations are written in italics or marked {abstract}.

Which UML diagram would you use to show the order of method calls between objects?

A sequence diagram. A class diagram shows only static structure, not the order of interactions.


Summary

  • UML is the OMG-standard visual modelling language (current version 2.5.1); the class diagram is its main structure diagram.

  • A class box has name, attributes, operations; syntax is visibility name : Type; visibility is + - # ~; static is underlined, abstract is italic, interfaces use «interface».

  • Relationships: association (solid line, optional arrow), aggregation (hollow ◇ at whole), composition (filled ◆ at whole), generalization (solid line, hollow △ to parent), realization (dashed line, hollow △ to interface), dependency (dashed arrow).

  • Multiplicity (1, 0..1, *, 1..*) is read at the far end and maps to single fields vs collections.

  • Diagrams and code should match: fields → associations, parameters → dependencies, extends/implements → triangles.

You now have the full OOP toolkit, from classes and the four pillars to SOLID, design patterns and UML. The final chapter, OOP Interview Questions, brings everything together for revision.