Skills101

AdvancedOOP Concepts · Lesson 13 of 16 · Updated ·

UML Class Diagrams to Java Code — Notation, Relationships and Multiplicity

A UML class diagram is a picture of the classes in a program and how they are connected. UML stands for Unified Modeling Language, a standard way of drawing software designs. University exams (software engineering and OOAD papers) ask you to draw one, and low-level design interviews ("design a library system") expect you to sketch one on a whiteboard before writing code.

The good news: a class diagram maps almost one-to-one to Java. Once you know the symbols, you can turn any diagram into code — and any code into a diagram.

1. The class box

A class is a rectangle with three parts: the name, the attributes (fields) and the operations (methods).

Anatomy of a UML class box for Book: name at the top, attributes with visibility symbols in the middle, operations with parameters and return types at the bottom

Each attribute is written visibility name : Type, and each operation visibility name(param : Type) : ReturnType. Note that UML puts the type after the name, while Java puts it before.

UML symbolJava visibility
+public
-private
#protected
~package-private (no keyword)

Two more rules: a static member is underlined, and an abstract class or method is written in italics (or marked {abstract}). An interface is shown with «interface» above its name.

The Book box above becomes:

public class Main {
    static class Book {
        private String isbn;
        private String title;
        private static int count = 0;      // underlined in UML

        public Book(String isbn, String title) {
            this.isbn = isbn;
            this.title = title;
            count++;
        }
        public String getTitle() { return title; }
        public boolean isIssuedTo(String memberId) { return false; }
        public static int getCount() { return count; }
    }

    public static void main(String[] args) {
        new Book("978-81-203-4007-7", "Let Us C");
        Book b = new Book("978-93-5213-008-2", "Core Java");
        System.out.println(b.getTitle() + " | books created: " + Book.getCount());
    }
}
Core Java | books created: 2

2. The six relationship lines

The lines between boxes carry most of the meaning. Learn these six:

The six UML relationship notations: association as a plain line, dependency as a dashed arrow, aggregation with a hollow diamond, composition with a filled diamond, inheritance with a hollow triangle and solid line, realization with a hollow triangle and dashed line

RelationshipDrawn asMeaningJava
Associationsolid line (optional open arrow)"knows / uses" for a long timea field of the other type
Dependencydashed open arrowuses brieflya parameter or local variable
Aggregationhollow diamond at the wholehas-a, parts can live alonefield holding objects created elsewhere
Compositionfilled diamond at the wholeowns, parts die with the wholethe whole creates its parts
Inheritance (generalisation)solid line, hollow triangle at the parentis-aextends
Realizationdashed line, hollow triangle at the interfaceimplementsimplements

A memory trick: the diamond always sits next to the whole (the container), and the triangle always points at the more general type.

3. Multiplicity: how many?

Numbers at each end of a line say how many objects take part:

MultiplicityMeaningJava
1exactly onea single field, never null
0..1zero or onea single field that may be null (or Optional)
* or 0..*any numbera List or Set
1..*at least onea List checked to be non-empty

Read multiplicity from the far end: on the line Member 1 ——— 0..* Loan, the 0..* next to Loan means "one member has zero or more loans", and the 1 next to Member means "each loan belongs to exactly one member".

4. A full example: a college library

Here is the design, written in text the way you might describe it in an exam:

  • Library ◆—— 1..* Shelf (composition: shelves are created by the library and do not exist without it)
  • Shelf ◇—— 0..* Book (aggregation: books can be moved to another shelf)
  • Member 1 —— 0..* Loan —— 1 Book (associations)
  • Loan uses java.time.LocalDate for the due date (dependency on a library class)
  • «interface» Notifiable is realized by Member

And the Java that follows the diagram line by line:

import java.util.*;

interface Notifiable {                        // «interface»
    String notifyMsg(String text);
}

class Book {
    private final String title;
    Book(String title) { this.title = title; }
    String getTitle() { return title; }
}

class Shelf {                                 // aggregation: books are passed in
    private final String code;
    private final List<Book> books = new ArrayList<>();   // 0..*
    Shelf(String code) { this.code = code; }
    void place(Book b) { books.add(b); }
    int size() { return books.size(); }
    String getCode() { return code; }
}

class Library {                               // composition: the library creates its shelves
    private final List<Shelf> shelves = new ArrayList<>(); // 1..*
    Library(int shelfCount) {
        if (shelfCount < 1) throw new IllegalArgumentException("need at least one shelf");
        for (int i = 1; i <= shelfCount; i++) shelves.add(new Shelf("S" + i));
    }
    Shelf shelf(int i) { return shelves.get(i); }
}

class Member implements Notifiable {          // realization
    private final String name;
    private final List<Loan> loans = new ArrayList<>();    // 1 member — 0..* loans
    Member(String name) { this.name = name; }
    Loan borrow(Book b) {
        Loan loan = new Loan(this, b);
        loans.add(loan);
        return loan;
    }
    int loanCount() { return loans.size(); }
    String getName() { return name; }
    public String notifyMsg(String text) { return "To " + name + ": " + text; }
}

class Loan {                                  // association to exactly 1 Member and 1 Book
    private final Member member;
    private final Book book;
    Loan(Member member, Book book) { this.member = member; this.book = book; }
    String describe() { return member.getName() + " has '" + book.getTitle() + "'"; }
}

public class Main {
    public static void main(String[] args) {
        Library lib = new Library(2);
        Book c = new Book("Let Us C");
        Book java = new Book("Core Java");
        lib.shelf(0).place(c);
        lib.shelf(0).place(java);
        System.out.println(lib.shelf(0).getCode() + " holds " + lib.shelf(0).size() + " books");

        Member asha = new Member("Asha");
        Loan loan = asha.borrow(java);
        System.out.println(loan.describe() + ", loans: " + asha.loanCount());
        System.out.println(asha.notifyMsg("return by Friday"));
    }
}
S1 holds 2 books
Asha has 'Core Java', loans: 1
To Asha: return by Friday

Notice how each symbol showed up in code: the filled diamond became "Library creates new Shelf(...) itself", the hollow diamond became "Shelf.place(Book) receives books made elsewhere", 0..* became a List, 1 became a final field set in the constructor, and the realization arrow became implements Notifiable.

5. Tips for exams and interviews

  1. Find the nouns first. In "members borrow books from the library", the nouns Member, Book, Library are candidate classes; verbs like borrow become methods or association classes (Loan).
  2. Show only what matters. Skip getters and setters unless asked; examiners want the important fields, methods and relationships.
  3. Label multiplicities on every association — it is the most commonly forgotten part and it carries marks.
  4. Check each diamond: if the part can exist on its own, it is aggregation (hollow); if it dies with the whole, composition (filled).
  5. Check each triangle: class → class is extends (solid line); class → interface is implements (dashed line).

Common mistakes

  • Putting the diamond at the wrong end. It belongs next to the whole, not the part.
  • Drawing an arrow from parent to child for inheritance. The triangle points to the parent.
  • Writing Java-style String title inside the box instead of UML-style title : String.
  • Using a solid line with a triangle for an interface. Implementing an interface is a dashed line.
  • Forgetting multiplicity, or reading it from the wrong end.

Quick recap

  • A class box has name, attributes (- title : String) and operations (+ getTitle() : String); + - # ~ give visibility, underline means static, italics mean abstract.
  • Six lines: association (solid), dependency (dashed arrow), aggregation (hollow diamond), composition (filled diamond), inheritance (solid line + hollow triangle), realization (dashed line + hollow triangle).
  • Multiplicity 1, 0..1, 0..*, 1..* becomes a field, an optional field, a list, or a non-empty list.
  • Diamonds sit at the whole; triangles point at the general type.

Practice what you learned

📝 Quiz: UML Class Diagrams5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →