Skip to lesson

Reading UML class diagrams

Designs are explained on whiteboards and in interviews with boxes and arrows, and the code has to match them. If you cannot read the arrows, you cannot follow how a pattern is built. This lesson teaches the few lines that matter.

Class boxes and visibility symbols

A UML class diagram is a drawing of classes as boxes and the links between them as lines and arrows. It shows the shape of a design at a glance, before or after the code is written.

A class box has three parts: the name on top, the fields in the middle and the methods at the bottom. Below, the ShopLite Product box, then the same box as Java.

Text
+-------------------------------------------+|                  Product                  |+-------------------------------------------+| - id: int                                 || - name: String                            || - price: double                           || # stock: int                              |+-------------------------------------------+| + Product(id, name, price, stock)         || + getName(): String                       || + isInStock(): boolean                    || ~ reduceStock(qty: int): void             |+-------------------------------------------+

Example 1 · The Product box as Java

ProductBoxDemo.javaJava
class Product {    private final int id;    private final String name;    private final double price;    protected int stock;               // #  protected
    public Product(int id, String name, double price, int stock) {   // +  public        this.id = id;        this.name = name;        this.price = price;        this.stock = stock;    }
    public String getName() {        return name;    }
    public boolean isInStock() {        return stock > 0;    }
    void reduceStock(int qty) {        // ~  package-private (no keyword)        stock -= qty;    }}
public class ProductBoxDemo {    public static void main(String[] args) {        Product earbuds = new Product(1, "Earbuds", 1499, 2);        System.out.println(earbuds.getName() + " in stock: " + earbuds.isInStock());        earbuds.reduceStock(2);        System.out.println(earbuds.getName() + " in stock: " + earbuds.isInStock());    }}
Output
Earbuds in stock: true
Earbuds in stock: false

What this code does

  • Each symbol maps to a keyword: - is private, # is protected, + is public, and ~ is no keyword at all (package-private).
  • reduceStock is package-private, so ProductBoxDemo can call it only because both classes are in the same file and package.

The symbol before each member is its visibility: + public, - private, # protected and ~ package-private (Java's default, no keyword). Types come after a colon, as in price: double.

Diagrams often leave out getters, constructors or types when they do not matter for the point being made.

Interfaces and abstract classes

An interface is marked «interface» and an abstract class is in italics or marked {abstract}. Below, the arrows point up to the type that is extended or implemented.

Text
        «interface»       PaymentMethod+ pay(amount: double): String             △             ┆   dashed line: implements   «abstract» BasePayment# name: String+ pay(amount: double): String# fee(amount: double): double {abstract}         △              △         │              │   solid line: extends    CardPayment     UpiPayment

Example 2 · An interface, an abstract class and two subclasses

InterfaceDiagramDemo.javaJava
interface PaymentMethod {    String pay(double amount);}
abstract class BasePayment implements PaymentMethod {    protected final String name;
    protected BasePayment(String name) {        this.name = name;    }
    public String pay(double amount) {        double fee = fee(amount);        return String.format("%s: Rs %.2f (fee Rs %.2f)", name, amount + fee, fee);    }
    protected abstract double fee(double amount);      // italic or {abstract} in UML}
class CardPayment extends BasePayment {    CardPayment() { super("Card"); }
    protected double fee(double amount) { return amount * 0.02; }}
class UpiPayment extends BasePayment {    UpiPayment() { super("UPI"); }
    protected double fee(double amount) { return 0; }}
public class InterfaceDiagramDemo {    public static void main(String[] args) {        PaymentMethod[] methods = { new CardPayment(), new UpiPayment() };        for (PaymentMethod m : methods) {            System.out.println(m.pay(1000));        }    }}
Output
Card: Rs 1020.00 (fee Rs 20.00)
UPI: Rs 1000.00 (fee Rs 0.00)

What this code does

  • The dashed triangle becomes BasePayment implements PaymentMethod; the two solid triangles become extends BasePayment.
  • fee is marked {abstract} in the diagram, so it is protected abstract in Java and each subclass must give it a body.

Read a diagram from the bottom up: "CardPayment extends BasePayment, which implements PaymentMethod." Abstract methods are marked the same way as abstract classes.

Arrows: inheritance, implementation, association, dependency

An association is a link where one class keeps a field of another type, drawn as a solid line with an open arrow, like Checkout holding a PaymentGateway. A dependency is a brief use, drawn dashed.

Four lines cover most diagrams. Below, each one is written in text next to the Java it means.

Text
CardPayment ────────▷ BasePayment      inheritance     (extends)BasePayment - - - - ▷ PaymentMethod    implementation  (implements)Checkout    ────────> PaymentGateway   association     (Checkout has a field of that type)Checkout    - - - - > Order            dependency      (uses it briefly: parameter, local, static call)
Five UML lines. Solid line with hollow triangle: inheritance, extends. Dashed with hollow triangle: implementation, implements. Solid open arrow: association, a field. Dashed open arrow: dependency, a parameter or local. Filled diamond: composition, the whole owns its parts.

Example 3 · Association versus dependency in code

ArrowsDemo.javaJava
interface PaymentGateway {    boolean charge(String orderId, double amount);}
class FakeGateway implements PaymentGateway {    public boolean charge(String orderId, double amount) {        return amount > 0;    }}
record Order(String id, double total) {}
class ReceiptFormat {    static String line(Order order) {        return String.format("%s Rs %.2f", order.id(), order.total());    }}
class Checkout {    private final PaymentGateway gateway;                       // association
    Checkout(PaymentGateway gateway) {        this.gateway = gateway;    }
    String pay(Order order) {                                   // dependency on Order        boolean ok = gateway.charge(order.id(), order.total());        return ReceiptFormat.line(order) + (ok ? " PAID" : " FAILED");   // dependency on ReceiptFormat    }}
public class ArrowsDemo {    public static void main(String[] args) {        Checkout checkout = new Checkout(new FakeGateway());        System.out.println(checkout.pay(new Order("ORD-81", 750)));        System.out.println(checkout.pay(new Order("ORD-82", 0)));    }}
Output
ORD-81 Rs 750.00 PAID
ORD-82 Rs 0.00 FAILED

What this code does

  • Checkout keeps a PaymentGateway in a field for its whole life: an association, drawn as a solid arrow.
  • Order arrives only as a parameter and ReceiptFormat is only called: both are dependencies, drawn as dashed arrows. FakeGateway to PaymentGateway is the dashed triangle.

A hollow triangle points to the parent type: solid for extends, dashed for implements. A dashed open arrow is a dependency: the class only uses the other type for a moment, as a parameter, a local variable or a static call.

Common mistake: drawing a solid arrow for something used only as a parameter. Ask whether the class keeps it in a field; if not, it is a dependency.

Predict the output

Pick the line

Read the Java and pick the UML line.

Round 1 of 2

Which line goes from Checkout to Order?

class Checkout {
private final PaymentGateway gateway;
boolean pay(Order order) { return gateway.charge(order.id(), order.total()); }
}
In plain text, people often write these as --|>, ..|>, --> and ..>, the notation used by tools such as PlantUML and Mermaid.

Aggregation, composition and multiplicity

In a UML diagram, composition is a strong has-a drawn with a filled diamond on the owner: the whole creates its parts and they do not outlive it, like the lines of an order.

A filled diamond marks ownership and a hollow diamond marks sharing. Below, an order with its lines, a category with its products, and a number at each line end.

Text
Order    ◆──────── "1..*" OrderLine    composition: the order owns its linesCategory ◇──────── "0..*" Product      aggregation: products live on their ownOrderLine ───────> "1"    Product      exactly one product per lineMultiplicity:  1  exactly one    0..1  zero or one    0..*  any number    1..*  at least one

Example 4 · Composition and aggregation with multiplicity

DiamondsDemo.javaJava
import java.util.ArrayList;import java.util.List;
record Product(String name, double price) {}
// Composition: Order ◆── "1..*" OrderLineclass OrderLine {    private final Product product;    private final int qty;
    OrderLine(Product product, int qty) {        this.product = product;        this.qty = qty;    }
    double amount() {        return product.price() * qty;    }}
class Order {    private final List<OrderLine> lines = new ArrayList<>();
    Order(Product first, int qty) {        addLine(first, qty);    }
    void addLine(Product product, int qty) {        lines.add(new OrderLine(product, qty));    }
    int lineCount() {        return lines.size();    }
    double total() {        double sum = 0;        for (OrderLine line : lines) sum += line.amount();        return sum;    }}
// Aggregation: Category ◇── "0..*" Productclass Category {    private final List<Product> products = new ArrayList<>();
    void add(Product product) {        products.add(product);    }
    int size() {        return products.size();    }}
public class DiamondsDemo {    public static void main(String[] args) {        Product earbuds = new Product("Earbuds", 1499);        Product hoodie = new Product("Hoodie", 899);
        Category electronics = new Category();        System.out.println("New category: " + electronics.size() + " products (0..* allows zero)");        electronics.add(earbuds);
        Order order = new Order(earbuds, 2);        order.addLine(hoodie, 1);        System.out.printf("ORD-91: %d lines, total Rs %.2f%n", order.lineCount(), order.total());
        order = null;                       // the order and its lines are gone        System.out.println("Earbuds still in the category: " + (electronics.size() == 1));    }}
Output
New category: 0 products (0..* allows zero)
ORD-91: 2 lines, total Rs 3897.00
Earbuds still in the category: true

What this code does

  • Order creates its OrderLine objects with new inside addLine, and nobody else holds them: composition, filled diamond.
  • Category only stores products made elsewhere; they stay alive after the order is gone: aggregation, hollow diamond.
  • The Order constructor takes a first product, which is how this code enforces 1..*.

A hollow diamond is aggregation: the whole groups parts that exist on their own, like products in a category. If the category disappears, the products stay.

The test in code: if the whole creates the part inside itself, it is composition; if the part is created outside and passed in, it is aggregation.

From a ShopLite diagram to Java and back

Multiplicity is the number at the end of a line that says how many objects sit at that end: 1 exactly one, 0..1 zero or one, 0..* any number and 1..* at least one.

To read a diagram as Java, go arrow by arrow. Below, the ShopLite order diagram as text lines, and the Java it becomes.

Text
Customer  "1" ───────> "0..*" OrderOrder     ◆─────────── "1..*" OrderLineOrderLine ───────────> "1"    ProductOrder     ───────────> "0..1" CouponCheckout  ───────────>        PaymentGateway «interface»Checkout  - - - - - ->        Order            (pay(order) parameter)

Example 5 · The ShopLite order diagram as Java

OrderDiagramDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Optional;
record Product(String name, double price) {}
record Coupon(String code, double off) {}
record OrderLine(Product product, int qty) {    double amount() {        return product.price() * qty;    }}
class Order {    private final String id;    private final List<OrderLine> lines = new ArrayList<>();    // ◆ "1..*" OrderLine    private Coupon coupon;                                        // "0..1" Coupon
    Order(String id, Product product, int qty) {        this.id = id;        lines.add(new OrderLine(product, qty));    }
    void add(Product product, int qty) {        lines.add(new OrderLine(product, qty));    }
    void apply(Coupon coupon) {        this.coupon = coupon;    }
    Optional<Coupon> coupon() {        return Optional.ofNullable(coupon);    }
    String id() {        return id;    }
    double total() {        double sum = 0;        for (OrderLine line : lines) sum += line.amount();        return sum - coupon().map(Coupon::off).orElse(0.0);    }}
class Customer {    private final String name;    private final List<Order> orders = new ArrayList<>();
    Customer(String name) {        this.name = name;    }
    void addOrder(Order order) {        orders.add(order);    }
    String summary() {        return "Orders for " + name + ": " + orders.size();    }}
interface PaymentGateway {    boolean charge(String orderId, double amount);}
class Checkout {    private final PaymentGateway gateway;
    Checkout(PaymentGateway gateway) {        this.gateway = gateway;    }
    boolean pay(Order order) {                                    // dependency        return gateway.charge(order.id(), order.total());    }}
public class OrderDiagramDemo {    public static void main(String[] args) {        Customer asha = new Customer("Asha");        System.out.println(asha.summary());
        Order order = new Order("ORD-95", new Product("Backpack", 1299), 1);        order.add(new Product("Pen set", 150), 2);        System.out.println("Coupon present? " + order.coupon().isPresent());        order.apply(new Coupon("FEST100", 100));        asha.addOrder(order);
        Checkout checkout = new Checkout((id, amount) -> {            System.out.printf("Charged Rs %.2f for %s%n", amount, id);            return true;        });        checkout.pay(order);        System.out.println(asha.summary());    }}
Output
Orders for Asha: 0
Coupon present? false
Charged Rs 1499.00 for ORD-95
Orders for Asha: 1

What this code does

  • Each line of the diagram became one thing in code: 0..* orders a List, 0..1 coupon a nullable field returned as Optional, the composition diamond lines created inside Order.
  • The total is 1299 + 2 × 150 − 100 = 1499. Checkout gets a lambda as its PaymentGateway, which the diagram does not need to show.

Each triangle becomes extends or implements, each association a field and each dependency a parameter or local variable. In Java, 1 is a required field, 0..1 a field that may be null (often returned as Optional), * a List, and 1..* needs a check in the constructor because a List can be empty.

To draw a diagram from code, go the other way: list the classes, draw an association for each field (with a diamond if the class creates the part itself) and a dashed dependency for each parameter type. Leave out details that do not help the reader.

Order of execution

Diagram to Java

Put the steps in the order that works for any diagram.

Next step

Check your understanding

10 quick questions