Skip to content
notes.vinhnq.com

Search

OOP & DesignMid15 min read

Object-oriented programming: UML class diagrams and the six class relationships

Review 13 cards
On this page

Object-oriented programming series: 1. Classes, objects, access modifiers · 2. Immutability, equals/hashCode, final · 3. Inheritance, encapsulation, polymorphism · 4. Abstract classes and interfaces · 5. UML, class relationships · 6. Wrappers, BigDecimal, String

Knowing the syntax of classes and objects, immutability and equals/hashCode, inheritance and interfaces isn’t enough: with a few dozen classes, the hard question is how they relate (who holds whom, who creates whom, does deleting one take another with it). This post teaches you to read and draw UML class diagrams, recognize the six class relationships and write them in code. The “foundation” classes (wrappers, BigInteger/BigDecimal, String, StringBuilder) are in part 6.

1. UML class diagrams

Key idea: a UML class diagram draws each class as a three-compartment box (name, attributes, methods) with visibility symbols. It exists to communicate a design, not to generate code.

UML (Unified Modeling Language) is the standard modeling language that lets a team look at the same design before coding. The class diagram is the UML diagram backend engineers use most: in design docs and in object-oriented (low-level) design interviews.

classDiagram
  class BankAccount {
    -String number
    -BigDecimal balance
    #String ownerName
    ~int branchCode
    +int MAX_DAILY_WITHDRAWALS$
    /BigDecimal availableBalance
    +BankAccount(String number, String ownerName)
    +deposit(BigDecimal amount) void
    +withdraw(BigDecimal amount) void
    +balance() BigDecimal
    +generateNumber()$ String
  }
Notation Meaning
+ public
- private
# protected
~ default (package-private)
underlined (Mermaid uses $) static member
italic (Mermaid uses *) abstract method
/ derived attribute: computed from other values, not stored (e.g. availableBalance = balance − holds)
«interface», «abstract», «enum» stereotype (a kind label), written above the name
  • Syntax: visibility name : Type for attributes, visibility name(param : Type) : ReturnType for methods. Mermaid puts the type before the name (Java-style); both styles are widely understood.
  • Draw only the classes and relationships that matter for your point. Nobody reads a 60-class diagram.

2. Six relationships between classes

Key idea: there are six relationships, from tightest to loosest: inheritance ≈ realization > composition > aggregation > association > dependency. Each is spotted by one question and has its own shape in code.

classDiagram
  direction LR
  Animal <|-- Dog : inheritance
  Comparable <|.. Money : realization
  Order *-- OrderLine : composition
  Team o-- Player : aggregation
  Driver --> Car : association
  ReportService ..> PdfRenderer : dependency
Relationship UML notation Question that identifies it In code
Inheritance (generalization) solid line, hollow triangle pointing at the parent “Is A a kind of B?” class A extends B
Realization dashed line, hollow triangle pointing at the interface “Does A promise to do what B describes?” class A implements B
Composition filled diamond on the whole’s side “Can’t the part live without the whole?” The whole creates and owns the part
Aggregation hollow diamond on the whole’s side “A has-a, but the part lives independently?” The part is created elsewhere and passed in
Association solid line (optionally with an arrow for direction) “Does A know about B long-term, ownership unclear?” A reference field
Dependency dashed arrow “Does A only use B temporarily?” Parameter, local variable, static call

2.1. Inheritance

A Dog is an Animal; a SavingsAccount is a BankAccount: the subclass gets the parent’s attributes and methods (see part 3).

abstract class BankAccount {
    protected BigDecimal balance = BigDecimal.ZERO;
    abstract BigDecimal monthlyFee();
}

class SavingsAccount extends BankAccount {
    @Override BigDecimal monthlyFee() { return BigDecimal.ZERO; }
}
Drawing several subclasses: separate target and shared target

When several subclasses extend the same parent (say Shape with Polygon, Ellipse and Spline), UML lets you draw it two ways:

  • Separate target: one arrow per subclass, each with its own triangle touching the parent.
  • Shared target: the lines merge into one tree that meets the parent at one shared triangle.

Both mean the same thing; the shared style is tidier with many subclasses.

2.2. Realization

The relationship between an interface and a class that implements it.

interface Notifier { void send(String to, String message); }

class EmailNotifier implements Notifier {
    @Override public void send(String to, String message) { /* talk to SMTP */ }
}

The slides (Vehicle implemented by Car and Ship) write the attribute as + $name, which is PHP variable syntax. In UML for Java, write +name: String.

2.3. Composition: “live together, die together”

The whole owns the part: the part is created inside the whole, isn’t shared, and is meaningless without it. Example: Order and OrderLine. Delete the order and its lines go too; a line can’t belong to two orders.

public class Order {
    private final List<OrderLine> lines = new ArrayList<>();   // created and managed by Order

    public void addItem(String sku, int qty, BigDecimal unitPrice) {
        lines.add(new OrderLine(sku, qty, unitPrice));          // the part is created INSIDE the whole
    }

    public List<OrderLine> lines() { return List.copyOf(lines); }   // never expose the internal list

    public BigDecimal total() {
        return lines.stream().map(OrderLine::subtotal).reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}

record OrderLine(String sku, int qty, BigDecimal unitPrice) {
    BigDecimal subtotal() { return unitPrice.multiply(BigDecimal.valueOf(qty)); }
}

In JPA, composition maps to @OneToMany(cascade = ALL, orphanRemoval = true) or @Embedded. In Domain-Driven Design (DDD), it’s an aggregate: Order is the aggregate root (the only door for changes), and every change to an OrderLine goes through Order so the invariants (rules that must always hold, e.g. the total never exceeds a credit limit) stay true.

The slides’ Human/Head/Body example: setters mean aggregation

2.4. Aggregation: “together, but independent”

The whole contains the part but doesn’t own its lifecycle: the part is created outside, passed in, and may belong to several wholes. Example: Team and Player. When a team disbands, its players still exist and can join another team.

public class Team {
    private final String name;
    private final List<Player> players = new ArrayList<>();

    public Team(String name) { this.name = name; }

    public void add(Player player) {                // the part is created OUTSIDE and passed in
        players.add(Objects.requireNonNull(player));
    }
}

Player messi = new Player("Messi");
Team miami = new Team("Inter Miami");
miami.add(messi);   // messi lives independently of miami

2.5. Association

Two classes know about each other long-term (usually through a field), without saying anything about ownership. A Driver references the Car they drive; a Student is associated with a Course. Associations have a direction (one-way or two-way) and a multiplicity (how many objects on each side): 1, 0..1, *, 1..*.

classDiagram
  Student "*" -- "*" Course : enrolls in
  Customer "1" --> "0..*" Order : places

The slides advise (rightly) using association during analysis, while the nature of a relationship is unclear, and pinning it down as composition, aggregation or plain dependency once you design.

2.6. Dependency

A uses B temporarily: B is a parameter, a local variable, a return type, or the target of a static call. A doesn’t hold on to B.

public class ReportService {
    public byte[] export(Report report, PdfRenderer renderer) {   // PdfRenderer is just a parameter
        return renderer.render(report);
    }
}

Spring constructor injection turns a dependency into a field (formally an association), but the field’s type is an interface: that’s the Dependency Inversion Principle, both sides depend on an abstraction (see IoC and Dependency Injection). Applied to a whole codebase (repository interface in the domain, JPA implementation at the edge), it is hexagonal and clean architecture; see Codebase architecture.

Composition over inheritance, concretely

A bigger example on business code: Template Method or composition refactors a booking flow from v0 to v2 with Template Method (inheritance), then rewrites it with composition (a list of rules and listeners assembled per type). Inheritance breaks once variants need to combine (“apartment + business guest + long stay”), since each subclass has only one parent; add traps like overriding a step and forgetting super, or calling an overridable method from a constructor.

Exercises

All solutions were run on JDK 21.

1. Draw a UML class diagram for the fraction class from the previous session

The Fraction class (full solution in part 2) has a private numerator and denominator, a constructor, a reduce method, a string conversion, and four operations that return new fractions.

Solution 1: the Fraction diagram and how to read it
classDiagram
  class Fraction {
    <<final>>
    -long numerator
    -long denominator
    +Fraction(long numerator, long denominator)
    +reduce() Fraction
    +add(Fraction other) Fraction
    +subtract(Fraction other) Fraction
    +multiply(Fraction other) Fraction
    +divide(Fraction other) Fraction
    +toString() String
    +equals(Object o) boolean
    +hashCode() int
    -gcd(long a, long b)$ long
  }
  class Object
  Object <|-- Fraction
  Fraction ..> ArithmeticException : throws when denominator = 0
  • Both fields are - (private) to protect the non-zero-denominator invariant.
  • gcd is private static (marked $, underlined in standard UML) because it doesn’t depend on object state.
  • The operations take and return a Fraction because the class is immutable.
  • toString, equals and hashCode override Object’s methods.
  • Fraction depends on ArithmeticException (dashed arrow), since it only uses it temporarily when throwing.

2. Write code that demonstrates the class-diagram relationships

Write a small e-commerce example that covers all six relationships.

Solution 2: an e-commerce example with all six relationships
// Realization
interface PaymentMethod { boolean pay(BigDecimal amount); }
class CardPayment implements PaymentMethod {
    @Override public boolean pay(BigDecimal amount) { return amount.signum() > 0; }
}

// Inheritance
abstract class User {
    protected final String id;
    User(String id) { this.id = id; }
}
class Customer extends User {
    private final List<Order> orders = new ArrayList<>();          // Association: 1 - * with Order
    Customer(String id) { super(id); }
    Order placeOrder() { Order o = new Order(this); orders.add(o); return o; }
}

// Composition: Order creates and owns its OrderLines
class Order {
    private final Customer customer;                                // association back to Customer
    private final List<OrderLine> lines = new ArrayList<>();
    Order(Customer customer) { this.customer = customer; }
    void addLine(Product product, int qty) { lines.add(new OrderLine(product, qty)); }
    BigDecimal total() {
        return lines.stream().map(OrderLine::subtotal).reduce(BigDecimal.ZERO, BigDecimal::add);
    }
    // Dependency: PaymentMethod is just a parameter
    boolean checkout(PaymentMethod method) { return method.pay(total()); }
}

record OrderLine(Product product, int qty) {
    BigDecimal subtotal() { return product.price().multiply(BigDecimal.valueOf(qty)); }
}

// Aggregation: Products exist independently; a Category just groups them
record Product(String sku, BigDecimal price) { }
class Category {
    private final List<Product> products = new ArrayList<>();
    void add(Product p) { products.add(p); }                        // the Product was created elsewhere
}

// Try it out
Product book = new Product("BOOK-1", new BigDecimal("120000"));
Category books = new Category();
books.add(book);
Customer c = new Customer("C1");
Order order = c.placeOrder();
order.addLine(book, 2);
System.out.println(order.total() + " " + order.checkout(new CardPayment()));   // 240000 true

Delete the Order and its OrderLines go with it (composition). Delete the Category and the Products remain (aggregation). Order uses PaymentMethod only during checkout (dependency).

Remember

  • Can you read a class box: + - # ~, underline, italics, /?
  • Can you list the six relationships in coupling order, with the UML notation and code shape of each?
  • Can you explain where composition differs from aggregation in code (who calls new) and in the database (cascade, orphan removal)?
  • Do you know why a setter that takes the part from outside rules out composition?
  • Can you state the direction of a dependency correctly: A depends on B when a change in B can force A to change?

Interview questions

Junior

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

Public, private, protected and package-private, respectively.

Static members are underlined, abstract methods are italic, and / marks a derived attribute (computed from other data).

How are inheritance and interface realization drawn differently in UML?

Both use a hollow triangle; inheritance is a solid line, realization a dashed one.

Inheritance (generalization) goes from the subclass to the parent; realization goes from the class to the interface. With several subclasses you can draw one arrow each or merge them into one shared triangle at the parent; both mean the same thing.

Mid

How do composition and aggregation differ, and how does that show up in code?

Composition: the whole creates and owns the part, which dies with it. Aggregation: the part is created elsewhere, passed in, and lives independently.

Examples: Order and OrderLine (composition), Team and Player (aggregation, can be shared). In code, the difference is who calls new and who owns the lifecycle. In the database, it shows up as cascade deletes and orphan removal.

How do association and dependency differ when you look at the code?

Association holds a long-lived reference (a field); dependency only uses B temporarily (parameter, local variable, return type, static call).

Examples: Driver has a Car field; ReportService.export(report, renderer) only receives the renderer as a parameter. Direction: A depends on B when a change in B can force A to change, and the dashed arrow goes from A to B.

Car has a public setEngine(Engine). Is Car–Engine a composition?

Not really: if the engine is created elsewhere, plugged in, and can be swapped or shared, Car doesn’t control its lifecycle, so it’s aggregation.

For composition, Car must create its own Engine (in its constructor or its own factory), expose no setter that takes an engine from outside, and the engine goes away with the car. In persistence, that maps to cascades and orphan removal.

Senior

How do you decide between composition and aggregation, and how does that affect persistence design?

By lifecycle and the consistency boundary: a part that only makes sense inside the whole is composition (a DDD aggregate); a part that lives independently is referenced by ID.

  • Composition: invariants are checked together; saved and deleted together, cascaded, modified only through the aggregate root, within one transaction.
  • Independent part referenced from many places: hold its ID instead of the object, and don’t cascade, so aggregates stay small and you don’t lock too many rows.
Outside interviews, when do you draw a UML class diagram, and how detailed do you make it?

When designing a new module with many interacting classes or reviewing a large change, and only the parts that matter for the decision at hand.

  • Example modules: a domain model, an aggregate, a set of strategies. Leave out getters, setters and minor fields.
  • Keep diagrams as code (Mermaid, PlantUML) in the repo so they’re reviewed with the code; a diagram that has drifted from the code is worse than none.
  • At the system level (services, databases, queues), use an architecture diagram such as C4 rather than a class diagram.

Useful phrases for interviews

  • “Let me sketch a quick class diagram first, so we agree on the relationships before we write code.”
  • “This is composition: the order owns the lifecycle of its lines, so they’re saved and deleted together.”
  • “Here it’s only aggregation; products exist independently, so I’d reference them by ID and avoid cascading.”
  • “Strictly speaking, A depends on B, because a change in B’s API would force A to change.”
  • “I’d wrap the collection rather than extend it; composition keeps us decoupled from the parent’s internals.”
  • “Generalization points from the subclass to the parent, and several subclasses can share one triangle.”
  • “If the class exposes a setter for its part, it’s really aggregation, not composition.”
  • “At analysis time I’d just draw an association; once we design, I pin it down as composition, aggregation or a dependency.”

Notes based on the Fundamentals of Backend course (Ronin Engineer), rewritten in my own words. The slides’ reference book is Y. Daniel Liang, Introduction to Java Programming and Data Structures (11th edition); many of their diagrams come from it.