Class Diagrams — Structure of Your System
Introduction
A class diagram shows the structure of a program: the classes it has, what each one holds, what each one can do, and how the classes are linked to each other. Introduction to UML — Why Visual Modeling Matters compared it to the floor plan of a building. A floor plan does not show people walking through the house or what happens in each room. It shows the rooms, their sizes and the doors between them, and a class diagram does the same for code. How objects call each other over time is the job of a sequence diagram, and a workflow's steps are the job of an activity diagram.
This page teaches you to read and draw one, on the library's lending system from Introduction to UML — Why Visual Modeling Matters. You will see how one class is drawn, the six kinds of line that link classes, the numbers that say how many objects take part, and then the library's whole diagram beside the code it describes. Each relationship has had a page of its own, from Association — Objects That Know Each Other to Generalization vs Specialization; a class diagram puts them together on one sheet.
Anatomy of a Class Box
UML describes the box in two sentences: "The default notation for a Classifier is a solid-outline rectangle containing the Classifier’s name, and with compartments separated by horizontal lines below the name. The name of the Classifier should be centered in boldface." A class is the most common kind of classifier, and its box usually has three compartments.
- The name sits at the top, bold and centered. An abstract class, like the ones in Interfaces vs Abstract Classes, has its name in italics: "The name of an abstract Classifier is shown in italics, where permitted by the font in use." Other kinds of classifier carry a keyword in guillemets above the name, such as «interface» or «enumeration». A plain class carries none, because "No keyword is needed to indicate that the metaclass is Class."
- The attributes are the data each object holds, one to a line in the form
visibility name: type, for example- title: String. - The operations are what Java and Python call methods, one to a line in the form
visibility name(parameters): returnType, for example+ getTitle(): String. An operation that returns nothing has no return type at all, since UML writes one only "if the Operation has one defined." SomarkAsBorrowedis drawn as+ markAsBorrowed(). Some diagrams write: voidthere, a word they take from Java or C++.
The types on this page are UML's own where it has one. String, Integer and Boolean are three of the primitive types UML defines, and they mean the same thing in every language. A class works as a type too, as in - status: BookStatus.
Two more rules come up often. A static member belongs to the class and is shared by all its objects, and UML marks it with a line under it: "Static Features are underlined." And a box does not have to show everything: "Any compartment may be suppressed." When one is left out, the reader should not guess at it, because "If a compartment is suppressed, no inference may be drawn about the presence or absence of elements in it."
Visibility
The symbol in front of each member says who may use it. UML has four:
| Symbol | Name | Who can use it |
|---|---|---|
+ | public | any code that can see the class |
- | private | only the class itself |
# | protected | the class and its subclasses |
~ | package | classes in the same package |
UML's own wording for the two most used is short. A private member "is only visible inside the Namespace that owns it", which for a member means its class. A protected one "is visible to Elements that have a generalization relationship to the Namespace that owns it", which means the class's subclasses.
Java, C++, TypeScript and C# have keywords for the first three. For ~, Java uses no keyword at all (a member with none is visible in its package), C# has internal, and C++ and TypeScript have no match. Python has no keywords for any of them: a leading underscore marks a name as private by agreement, as Encapsulation — Data Hiding Done Right explains. Go decides by the first letter: a name that starts with a capital letter can be used outside its package, and any other name cannot.
The Relationships and Their Notation
Every line between two boxes is one of six relationships. Two things tell them apart: whether the line is solid or dashed, and what shape sits at its ends. Here they are on the library's own classes, each with the page that teaches it:
- Association, a solid line: an object keeps a link to another. A
Memberkeeps its loans. An open arrowhead says which way the link can be followed: "An open arrowhead on the end of an Association indicates the end is navigable." A member can reach itsLoanobjects and a loan does not know its member, so the arrow points atLoan. See Association — Objects That Know Each Other. - Aggregation, a hollow diamond at the whole: the whole holds parts that were made somewhere else and can outlive it. The
LibraryholdsBookobjects that the program made first and then added. See Aggregation — Has-A with Independent Lifecycle. - Composition, a filled diamond at the whole: the whole makes the part, and the part lives only inside it. A
Loanmakes its ownFinewhen a book comes back late and never hands it out. See Composition — Has-A with Dependent Lifecycle. - Generalization, a solid line with a hollow triangle at the parent: inheritance, the is-a relationship. A
Librarianis aMember. See Generalization vs Specialization. - Realization, a dashed line with a hollow triangle at the interface: a class implements an interface.
LibraryimplementsSearchable. See Realization — A Class Fulfilling an Interface. - Dependency, a dashed line with an open arrowhead at the class being used: one class uses another for a moment and keeps nothing.
Librarymakes aLoanand hands it over, and the keyword «Create» on the line says what kind of use it is. See Dependency — Objects That Use Each Other.
Multiplicity
The numbers at the ends of an association say how many objects take part, each written at the end it counts. A * next to Loan on the line from Member says a member has any number of loans, and a 1 next to Member says each loan belongs to exactly one member.
| Symbol | Meaning |
|---|---|
1 | exactly one |
0..1 | zero or one, so it may be missing |
* | zero or more |
1..* | one or more |
2..5 | between 2 and 5 |
Two of these are short forms. UML explains that "“1” is semantically equivalent to “1..1” multiplicity", and a star on its own means zero or more, the same as 0..*.
An end can also carry a name, and UML allows it in so many words: "A name string may be placed near the end of the line to show the name of the Association end." The name is the name of the field that holds the link, with its visibility in front. In the library's diagram below, - loans at the Loan end of the line from Member is the private field loans of Member.
The card puts all of this on one sheet:

Complete Example: The Library Class Diagram
Here is the library's whole class diagram, drawn from the listing further down this page. Each box is one class of the code, and each line is a link that the code makes:
![The class diagram of the library listing: eight boxes and eight lines. Top row: the interface Searchable, marked «interface», with the operation search(query: String) returning Book [*]; Library, with add(book: Book), search(query: String) returning Book [*] and lend(isbn: String, day: Integer) returning Loan; Book, with the private attributes title, author and isbn (String) and status (BookStatus), and the public operations getTitle, getIsbn, getStatus, isAvailable returning Boolean, matches(query: String) returning Boolean, markAsBorrowed and markAsReturned; and the enumeration BookStatus, marked «enumeration», with AVAILABLE, BORROWED, RESERVED and LOST, drawn with no line because it is the type of the status attribute. Bottom row: Librarian, with the private employeeId (String) and getEmployeeId; Member, with the private name (String) and getName, borrow(isbn: String, day: Integer) returning Loan, owes returning Integer and payFines; Loan, with the private dueDay (Integer) and the static, underlined LOAN_DAYS = 14 and DAILY_FINE = 50, and getDueDay, giveBack(day: Integer), fineDue returning Integer and payFine; Fine, with the private cents (Integer) and paid (Boolean), and due returning Integer and pay. The lines: Library realizes Searchable, a dashed line with a hollow triangle at Searchable. Library aggregates Book, a hollow diamond at Library and an arrow at Book, the end named - books with multiplicity any number, and 0..1 at Library. Library depends on Loan, a dashed arrow marked «Create». Member has a link to Library, an arrow at Library named - library with multiplicity 1, and any number at Member. Member has a link to Loan, an arrow at Loan named - loans with any number, and 1 at Member. Loan has a link to Book, an arrow at Book named - book with 1, and any number at Loan. Loan is composed of Fine, a filled diamond at Loan and an arrow at Fine named - fine with 0..1, and 1 at Loan. Librarian generalizes to Member, a solid line with a hollow triangle at Member.](https://pub-a1b3030acfb94e84ba8a89fb182c53bc.r2.dev/public/lld-content-3f9d6797-e8ff-4b8d-8935-43af218a898e/library-class-diagram.webp)
Read it a line at a time.
LibraryrealizesSearchable: it has thesearchoperation the interface asks for.LibraryaggregatesBookthrough- books, with*at the book's end: a library holds any number of books, which the program makes first and then adds. The0..1at the library's end says a book sits in at most one library.Librarydepends onLoan, marked «Create»:lendmakes a loan and hands it over without keeping it.Memberlinks toLibrarythrough- library, exactly one, and a library has any number of members, the*at the member's end.Memberlinks toLoanthrough- loans, any number, and each loan belongs to exactly one member.Loanlinks toBookthrough- book, exactly one. A book has any number of loans over its life, a new one each time it goes out.Loanis composed ofFinethrough- fine,0..1: a loan has no fine until its book comes back late, and then it makes one.Librarianis aMember: it borrows like any member and adds an employee id.
Three details are worth a second look. LOAN_DAYS and DAILY_FINE in Loan are underlined because they are static: they belong to the class, so every loan uses the same 14 days and 50 cents a day. BookStatus has no line at all. Book names it as the type of its status attribute, and an attribute is one of the ways UML draws a link, because "an Association end owned by a Class is also an attribute." Finally, the fields that point at other classes, such as loans and fine, appear on the lines and not again in the boxes. UML allows both at once but says the attribute "would typically be suppressed on grounds of redundancy", so each link here is drawn one time.
Translating a Class Diagram to Code
Here is the code the diagram was drawn from, in six languages. It adds two books, searches them, lends one, turns a second borrower away, takes the book back three days late and settles the fine. Days are plain numbers so that the program prints the same in every language; a real system would use its language's date type:
from abc import ABC, abstractmethod
from enum import Enum
# «enumeration» BookStatus in the diagram: a Python Enum
class BookStatus(Enum):
AVAILABLE = "AVAILABLE"
BORROWED = "BORROWED"
RESERVED = "RESERVED"
LOST = "LOST"
# «interface» Searchable: Python has no interface keyword; an abstract class plays it
class Searchable(ABC):
@abstractmethod
def search(self, query: str) -> list["Book"]: ... # Book [*]: any number, so a list
# A leading underscore is Python's mark for "private" (a convention, not a lock)
class Book:
def __init__(self, title: str, author: str, isbn: str) -> None:
self._title = title
self._author = author
self._isbn = isbn
self._status = BookStatus.AVAILABLE # - status: BookStatus
def get_title(self) -> str:
return self._title
def get_isbn(self) -> str:
return self._isbn
def get_status(self) -> BookStatus:
return self._status
def is_available(self) -> bool:
return self._status == BookStatus.AVAILABLE
def matches(self, query: str) -> bool:
q = query.lower()
return q in self._title.lower() or q in self._author.lower()
def mark_as_borrowed(self) -> None:
self._status = BookStatus.BORROWED
def mark_as_returned(self) -> None:
self._status = BookStatus.AVAILABLE
# Composition: a Fine is made by one Loan and lives inside it
class Fine:
def __init__(self, cents: int) -> None:
self._cents = cents
self._paid = False
def due(self) -> int:
return 0 if self._paid else self._cents
def pay(self) -> None:
self._paid = True
class Loan:
LOAN_DAYS = 14 # a class attribute: static, so underlined in the diagram
DAILY_FINE = 50 # cents for each day late
def __init__(self, book: Book, day: int) -> None:
self._book = book # - book, multiplicity 1: one reference
self._due_day = day + Loan.LOAN_DAYS
self._fine: Fine | None = None # - fine, multiplicity 0..1
def get_due_day(self) -> int:
return self._due_day
def give_back(self, day: int) -> None:
self._book.mark_as_returned()
days_late = day - self._due_day
if days_late > 0:
# the loan makes its own fine
self._fine = Fine(days_late * Loan.DAILY_FINE)
def fine_due(self) -> int:
return 0 if self._fine is None else self._fine.due()
def pay_fine(self) -> None:
if self._fine is not None:
self._fine.pay()
# Realization: Library implements Searchable
class Library(Searchable):
def __init__(self) -> None:
# - books, multiplicity *: a list of books made elsewhere (aggregation)
self._books: list[Book] = []
def add(self, book: Book) -> None:
self._books.append(book)
def search(self, query: str) -> list[Book]:
return [book for book in self._books if book.matches(query)]
# «Create»: the library makes a Loan and hands it over without keeping it
def lend(self, isbn: str, day: int) -> Loan:
for book in self._books:
if book.get_isbn() == isbn:
if not book.is_available():
raise RuntimeError(
f"{book.get_title()} is {book.get_status().value}")
book.mark_as_borrowed()
return Loan(book, day)
raise ValueError(f"No book with ISBN {isbn}")
class Member:
def __init__(self, name: str, library: Library) -> None:
self._name = name
self._library = library # - library, multiplicity 1
self._loans: list[Loan] = [] # - loans, multiplicity *
def get_name(self) -> str:
return self._name
def borrow(self, isbn: str, day: int) -> Loan:
loan = self._library.lend(isbn, day)
self._loans.append(loan)
return loan
def owes(self) -> int:
return sum(loan.fine_due() for loan in self._loans)
def pay_fines(self) -> None:
for loan in self._loans:
loan.pay_fine()
# Generalization: a Librarian is a Member and adds an employee id
class Librarian(Member):
def __init__(self, name: str, library: Library, employee_id: str) -> None:
super().__init__(name, library)
self._employee_id = employee_id
def get_employee_id(self) -> str:
return self._employee_id
def dollars(cents: int) -> str:
return f"${cents // 100}.{cents % 100:02d}"
library = Library()
clean_code = Book("Clean Code", "Robert C. Martin", "978-0132350884")
library.add(clean_code)
library.add(Book("Refactoring", "Martin Fowler", "978-0134757599"))
for book in library.search("martin"):
print(f"Found: {book.get_title()}")
alice = Member("Alice", library)
bob = Librarian("Bob", library, "E-101")
loan = alice.borrow("978-0132350884", 2)
print(f"{alice.get_name()} borrowed Clean Code on day 2, "
f"due back on day {loan.get_due_day()}")
try:
bob.borrow("978-0132350884", 3)
except RuntimeError as e:
print(f"{bob.get_name()} ({bob.get_employee_id()}) is turned away: {e}")
loan.give_back(19)
print(f"Back on day 19, the book is {clean_code.get_status().value} and "
f"{alice.get_name()} owes {dollars(alice.owes())}")
alice.pay_fines()
print(f"After paying, {alice.get_name()} owes {dollars(alice.owes())}")import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
// «enumeration» BookStatus in the diagram: a Java enum
enum BookStatus { AVAILABLE, BORROWED, RESERVED, LOST }
// «interface» Searchable: a Java interface
interface Searchable {
List<Book> search(String query); // Book [*]: any number of books, so a list
}
class Book {
private final String title;
private final String author;
private final String isbn;
private BookStatus status = BookStatus.AVAILABLE; // - status: BookStatus
public Book(String title, String author, String isbn) {
this.title = title;
this.author = author;
this.isbn = isbn;
}
public String getTitle() { return title; }
public String getIsbn() { return isbn; }
public BookStatus getStatus() { return status; }
public boolean isAvailable() { return status == BookStatus.AVAILABLE; }
public boolean matches(String query) {
String q = query.toLowerCase(Locale.ROOT);
return title.toLowerCase(Locale.ROOT).contains(q)
|| author.toLowerCase(Locale.ROOT).contains(q);
}
public void markAsBorrowed() { status = BookStatus.BORROWED; }
public void markAsReturned() { status = BookStatus.AVAILABLE; }
}
// Composition: a Fine is made by one Loan and lives inside it
class Fine {
private final int cents;
private boolean paid = false;
public Fine(int cents) { this.cents = cents; }
public int due() { return paid ? 0 : cents; }
public void pay() { paid = true; }
}
class Loan {
private static final int LOAN_DAYS = 14; // static: underlined in the diagram
private static final int DAILY_FINE = 50; // cents for each day late
private final Book book; // - book, multiplicity 1: one reference
private final int dueDay;
private Fine fine; // - fine, multiplicity 0..1: null until a late return
public Loan(Book book, int day) {
this.book = book;
this.dueDay = day + LOAN_DAYS;
}
public int getDueDay() { return dueDay; }
public void giveBack(int day) {
book.markAsReturned();
int daysLate = day - dueDay;
if (daysLate > 0) {
fine = new Fine(daysLate * DAILY_FINE); // the loan makes its own fine
}
}
public int fineDue() { return fine == null ? 0 : fine.due(); }
public void payFine() {
if (fine != null) {
fine.pay();
}
}
}
// Realization: Library implements Searchable
class Library implements Searchable {
// - books, multiplicity *: a list of books made elsewhere (aggregation)
private final List<Book> books = new ArrayList<>();
public void add(Book book) { books.add(book); }
@Override
public List<Book> search(String query) {
List<Book> found = new ArrayList<>();
for (Book book : books) {
if (book.matches(query)) {
found.add(book);
}
}
return found;
}
// «Create»: the library makes a Loan and hands it over without keeping it
public Loan lend(String isbn, int day) {
for (Book book : books) {
if (book.getIsbn().equals(isbn)) {
if (!book.isAvailable()) {
throw new IllegalStateException(
book.getTitle() + " is " + book.getStatus());
}
book.markAsBorrowed();
return new Loan(book, day);
}
}
throw new IllegalArgumentException("No book with ISBN " + isbn);
}
}
class Member {
private final String name;
private final Library library; // - library, multiplicity 1
private final List<Loan> loans = new ArrayList<>(); // - loans, multiplicity *
public Member(String name, Library library) {
this.name = name;
this.library = library;
}
public String getName() { return name; }
public Loan borrow(String isbn, int day) {
Loan loan = library.lend(isbn, day);
loans.add(loan);
return loan;
}
public int owes() {
int total = 0;
for (Loan loan : loans) {
total += loan.fineDue();
}
return total;
}
public void payFines() {
for (Loan loan : loans) {
loan.payFine();
}
}
}
// Generalization: a Librarian is a Member and adds an employee id
class Librarian extends Member {
private final String employeeId;
public Librarian(String name, Library library, String employeeId) {
super(name, library);
this.employeeId = employeeId;
}
public String getEmployeeId() { return employeeId; }
}
public class LibraryDemo {
static String dollars(int cents) {
return "$" + cents / 100 + "." + (cents % 100 < 10 ? "0" : "") + cents % 100;
}
public static void main(String[] args) {
Library library = new Library();
Book cleanCode = new Book("Clean Code", "Robert C. Martin", "978-0132350884");
library.add(cleanCode);
library.add(new Book("Refactoring", "Martin Fowler", "978-0134757599"));
for (Book book : library.search("martin")) {
System.out.println("Found: " + book.getTitle());
}
Member alice = new Member("Alice", library);
Librarian bob = new Librarian("Bob", library, "E-101");
Loan loan = alice.borrow("978-0132350884", 2);
System.out.println(alice.getName() + " borrowed Clean Code on day 2, "
+ "due back on day " + loan.getDueDay());
try {
bob.borrow("978-0132350884", 3);
} catch (IllegalStateException e) {
System.out.println(bob.getName() + " (" + bob.getEmployeeId()
+ ") is turned away: " + e.getMessage());
}
loan.giveBack(19);
System.out.println("Back on day 19, the book is " + cleanCode.getStatus()
+ " and " + alice.getName() + " owes " + dollars(alice.owes()));
alice.payFines();
System.out.println("After paying, " + alice.getName() + " owes "
+ dollars(alice.owes()));
}
}#include <cctype>
#include <cstdio>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
// «enumeration» BookStatus in the diagram: a C++ enum class
enum class BookStatus { AVAILABLE, BORROWED, RESERVED, LOST };
std::string toString(BookStatus status) {
switch (status) {
case BookStatus::AVAILABLE: return "AVAILABLE";
case BookStatus::BORROWED: return "BORROWED";
case BookStatus::RESERVED: return "RESERVED";
case BookStatus::LOST: return "LOST";
}
return "?";
}
std::string lower(std::string s) {
for (char& c : s) {
c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
return s;
}
class Book;
// «interface» Searchable: C++ has no interface keyword; a class of pure virtual methods
class Searchable {
public:
virtual ~Searchable() = default;
// Book [*]: any number of books, so a vector
virtual std::vector<Book*> search(const std::string& query) const = 0;
};
class Book {
public:
Book(std::string title, std::string author, std::string isbn)
: title_(std::move(title)), author_(std::move(author)),
isbn_(std::move(isbn)) {}
const std::string& getTitle() const { return title_; }
const std::string& getIsbn() const { return isbn_; }
BookStatus getStatus() const { return status_; }
bool isAvailable() const { return status_ == BookStatus::AVAILABLE; }
bool matches(const std::string& query) const {
std::string q = lower(query);
return lower(title_).find(q) != std::string::npos
|| lower(author_).find(q) != std::string::npos;
}
void markAsBorrowed() { status_ = BookStatus::BORROWED; }
void markAsReturned() { status_ = BookStatus::AVAILABLE; }
private:
std::string title_;
std::string author_;
std::string isbn_;
BookStatus status_ = BookStatus::AVAILABLE; // - status: BookStatus
};
// Composition: a Fine is made by one Loan and lives inside it
class Fine {
public:
explicit Fine(int cents) : cents_(cents) {}
int due() const { return paid_ ? 0 : cents_; }
void pay() { paid_ = true; }
private:
int cents_;
bool paid_ = false;
};
class Loan {
public:
Loan(Book& book, int day) : book_(&book), dueDay_(day + LOAN_DAYS) {}
int getDueDay() const { return dueDay_; }
void giveBack(int day) {
book_->markAsReturned();
int daysLate = day - dueDay_;
if (daysLate > 0) {
// the loan makes its own fine, and unique_ptr says it owns it
fine_ = std::make_unique<Fine>(daysLate * DAILY_FINE);
}
}
int fineDue() const { return fine_ ? fine_->due() : 0; }
void payFine() {
if (fine_) fine_->pay();
}
private:
static constexpr int LOAN_DAYS = 14; // static: underlined in the diagram
static constexpr int DAILY_FINE = 50; // cents for each day late
Book* book_; // - book, multiplicity 1: one pointer it does not own
int dueDay_;
std::unique_ptr<Fine> fine_; // - fine, multiplicity 0..1: empty until a late return
};
// Realization: Library implements Searchable
class Library : public Searchable {
public:
void add(Book& book) { books_.push_back(&book); }
std::vector<Book*> search(const std::string& query) const override {
std::vector<Book*> found;
for (Book* book : books_) {
if (book->matches(query)) found.push_back(book);
}
return found;
}
// «Create»: the library makes a Loan and hands it over without keeping it
std::unique_ptr<Loan> lend(const std::string& isbn, int day) {
for (Book* book : books_) {
if (book->getIsbn() == isbn) {
if (!book->isAvailable()) {
throw std::runtime_error(book->getTitle() + " is "
+ toString(book->getStatus()));
}
book->markAsBorrowed();
return std::make_unique<Loan>(*book, day);
}
}
throw std::invalid_argument("No book with ISBN " + isbn);
}
private:
// - books, multiplicity *: pointers to books made elsewhere (aggregation)
std::vector<Book*> books_;
};
class Member {
public:
Member(std::string name, Library& library)
: name_(std::move(name)), library_(&library) {}
virtual ~Member() = default;
const std::string& getName() const { return name_; }
Loan& borrow(const std::string& isbn, int day) {
loans_.push_back(library_->lend(isbn, day));
return *loans_.back();
}
int owes() const {
int total = 0;
for (const auto& loan : loans_) total += loan->fineDue();
return total;
}
void payFines() {
for (auto& loan : loans_) loan->payFine();
}
private:
std::string name_;
Library* library_; // - library, multiplicity 1
std::vector<std::unique_ptr<Loan>> loans_; // - loans, multiplicity *
};
// Generalization: a Librarian is a Member and adds an employee id
class Librarian : public Member {
public:
Librarian(std::string name, Library& library, std::string employeeId)
: Member(std::move(name), library), employeeId_(std::move(employeeId)) {}
const std::string& getEmployeeId() const { return employeeId_; }
private:
std::string employeeId_;
};
std::string dollars(int cents) {
char text[32];
std::snprintf(text, sizeof text, "$%d.%02d", cents / 100, cents % 100);
return text;
}
int main() {
Library library;
Book cleanCode("Clean Code", "Robert C. Martin", "978-0132350884");
Book refactoring("Refactoring", "Martin Fowler", "978-0134757599");
library.add(cleanCode);
library.add(refactoring);
for (Book* book : library.search("martin")) {
std::printf("Found: %s\n", book->getTitle().c_str());
}
Member alice("Alice", library);
Librarian bob("Bob", library, "E-101");
Loan& loan = alice.borrow("978-0132350884", 2);
std::printf("%s borrowed Clean Code on day 2, due back on day %d\n",
alice.getName().c_str(), loan.getDueDay());
try {
bob.borrow("978-0132350884", 3);
} catch (const std::runtime_error& e) {
std::printf("%s (%s) is turned away: %s\n", bob.getName().c_str(),
bob.getEmployeeId().c_str(), e.what());
}
loan.giveBack(19);
std::printf("Back on day 19, the book is %s and %s owes %s\n",
toString(cleanCode.getStatus()).c_str(), alice.getName().c_str(),
dollars(alice.owes()).c_str());
alice.payFines();
std::printf("After paying, %s owes %s\n", alice.getName().c_str(),
dollars(alice.owes()).c_str());
return 0;
}// «enumeration» BookStatus in the diagram: a TypeScript string enum
enum BookStatus {
AVAILABLE = "AVAILABLE",
BORROWED = "BORROWED",
RESERVED = "RESERVED",
LOST = "LOST",
}
// «interface» Searchable: a TypeScript interface
interface Searchable {
search(query: string): Book[]; // Book [*]: any number of books, so an array
}
class Book {
private status: BookStatus = BookStatus.AVAILABLE; // - status: BookStatus
constructor(
private readonly title: string,
private readonly author: string,
private readonly isbn: string,
) {}
getTitle(): string {
return this.title;
}
getIsbn(): string {
return this.isbn;
}
getStatus(): BookStatus {
return this.status;
}
isAvailable(): boolean {
return this.status === BookStatus.AVAILABLE;
}
matches(query: string): boolean {
const q = query.toLowerCase();
const inTitle = this.title.toLowerCase().includes(q);
return inTitle || this.author.toLowerCase().includes(q);
}
markAsBorrowed(): void {
this.status = BookStatus.BORROWED;
}
markAsReturned(): void {
this.status = BookStatus.AVAILABLE;
}
}
// Composition: a Fine is made by one Loan and lives inside it
class Fine {
private paid = false;
constructor(private readonly cents: number) {}
due(): number {
return this.paid ? 0 : this.cents;
}
pay(): void {
this.paid = true;
}
}
class Loan {
private static readonly LOAN_DAYS = 14; // static: underlined in the diagram
private static readonly DAILY_FINE = 50; // cents for each day late
private readonly dueDay: number;
private fine: Fine | null = null; // - fine, multiplicity 0..1
// - book, multiplicity 1: one reference
constructor(private readonly book: Book, day: number) {
this.dueDay = day + Loan.LOAN_DAYS;
}
getDueDay(): number {
return this.dueDay;
}
giveBack(day: number): void {
this.book.markAsReturned();
const daysLate = day - this.dueDay;
if (daysLate > 0) {
this.fine = new Fine(daysLate * Loan.DAILY_FINE); // the loan makes its own fine
}
}
fineDue(): number {
return this.fine === null ? 0 : this.fine.due();
}
payFine(): void {
if (this.fine !== null) {
this.fine.pay();
}
}
}
// Realization: Library implements Searchable
class Library implements Searchable {
// - books, multiplicity *: an array of books made elsewhere (aggregation)
private readonly books: Book[] = [];
add(book: Book): void {
this.books.push(book);
}
search(query: string): Book[] {
return this.books.filter((book) => book.matches(query));
}
// «Create»: the library makes a Loan and hands it over without keeping it
lend(isbn: string, day: number): Loan {
for (const book of this.books) {
if (book.getIsbn() === isbn) {
if (!book.isAvailable()) {
throw new Error(`${book.getTitle()} is ${book.getStatus()}`);
}
book.markAsBorrowed();
return new Loan(book, day);
}
}
throw new Error(`No book with ISBN ${isbn}`);
}
}
class Member {
private readonly loans: Loan[] = []; // - loans, multiplicity *
// - library, multiplicity 1
constructor(private readonly name: string, private readonly library: Library) {}
getName(): string {
return this.name;
}
borrow(isbn: string, day: number): Loan {
const loan = this.library.lend(isbn, day);
this.loans.push(loan);
return loan;
}
owes(): number {
return this.loans.reduce((total, loan) => total + loan.fineDue(), 0);
}
payFines(): void {
for (const loan of this.loans) {
loan.payFine();
}
}
}
// Generalization: a Librarian is a Member and adds an employee id
class Librarian extends Member {
constructor(name: string, library: Library, private readonly employeeId: string) {
super(name, library);
}
getEmployeeId(): string {
return this.employeeId;
}
}
function dollars(cents: number): string {
return `$${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
}
const library = new Library();
const cleanCode = new Book("Clean Code", "Robert C. Martin", "978-0132350884");
library.add(cleanCode);
library.add(new Book("Refactoring", "Martin Fowler", "978-0134757599"));
for (const book of library.search("martin")) {
console.log(`Found: ${book.getTitle()}`);
}
const alice = new Member("Alice", library);
const bob = new Librarian("Bob", library, "E-101");
const loan = alice.borrow("978-0132350884", 2);
console.log(
`${alice.getName()} borrowed Clean Code on day 2, ` +
`due back on day ${loan.getDueDay()}`,
);
try {
bob.borrow("978-0132350884", 3);
} catch (e) {
if (!(e instanceof Error)) throw e;
console.log(`${bob.getName()} (${bob.getEmployeeId()}) is turned away: ${e.message}`);
}
loan.giveBack(19);
console.log(
`Back on day 19, the book is ${cleanCode.getStatus()} and ` +
`${alice.getName()} owes ${dollars(alice.owes())}`,
);
alice.payFines();
console.log(`After paying, ${alice.getName()} owes ${dollars(alice.owes())}`);using System;
using System.Collections.Generic;
using System.Linq;
// «enumeration» BookStatus in the diagram: a C# enum
public enum BookStatus { AVAILABLE, BORROWED, RESERVED, LOST }
// «interface» Searchable: a C# interface, named with C#'s I prefix
public interface ISearchable
{
List<Book> Search(string query); // Book [*]: any number of books, so a list
}
public class Book
{
private readonly string author;
public Book(string title, string author, string isbn)
{
Title = title;
this.author = author;
Isbn = isbn;
}
// C# writes a getter as a read-only property
public string Title { get; }
public string Isbn { get; }
public BookStatus Status { get; private set; } = BookStatus.AVAILABLE;
public bool IsAvailable() => Status == BookStatus.AVAILABLE;
public bool Matches(string query)
{
string q = query.ToLowerInvariant();
return Title.ToLowerInvariant().Contains(q)
|| author.ToLowerInvariant().Contains(q);
}
public void MarkAsBorrowed() => Status = BookStatus.BORROWED;
public void MarkAsReturned() => Status = BookStatus.AVAILABLE;
}
// Composition: a Fine is made by one Loan and lives inside it
public class Fine
{
private readonly int cents;
private bool paid;
public Fine(int cents)
{
this.cents = cents;
}
public int Due() => paid ? 0 : cents;
public void Pay() => paid = true;
}
public class Loan
{
private const int LoanDays = 14; // static: underlined in the diagram
private const int DailyFine = 50; // cents for each day late
private readonly Book book; // - book, multiplicity 1: one reference
private Fine? fine; // - fine, multiplicity 0..1: null until a late return
public Loan(Book book, int day)
{
this.book = book;
DueDay = day + LoanDays;
}
public int DueDay { get; }
public void GiveBack(int day)
{
book.MarkAsReturned();
int daysLate = day - DueDay;
if (daysLate > 0)
{
fine = new Fine(daysLate * DailyFine); // the loan makes its own fine
}
}
public int FineDue() => fine == null ? 0 : fine.Due();
public void PayFine() => fine?.Pay();
}
// Realization: Library implements ISearchable
public class Library : ISearchable
{
// - books, multiplicity *: a list of books made elsewhere (aggregation)
private readonly List<Book> books = new();
public void Add(Book book) => books.Add(book);
public List<Book> Search(string query) =>
books.Where(book => book.Matches(query)).ToList();
// «Create»: the library makes a Loan and hands it over without keeping it
public Loan Lend(string isbn, int day)
{
foreach (Book book in books)
{
if (book.Isbn == isbn)
{
if (!book.IsAvailable())
{
throw new InvalidOperationException(
$"{book.Title} is {book.Status}");
}
book.MarkAsBorrowed();
return new Loan(book, day);
}
}
throw new ArgumentException($"No book with ISBN {isbn}");
}
}
public class Member
{
private readonly Library library; // - library, multiplicity 1
private readonly List<Loan> loans = new(); // - loans, multiplicity *
public Member(string name, Library library)
{
Name = name;
this.library = library;
}
public string Name { get; }
public Loan Borrow(string isbn, int day)
{
Loan loan = library.Lend(isbn, day);
loans.Add(loan);
return loan;
}
public int Owes() => loans.Sum(loan => loan.FineDue());
public void PayFines()
{
foreach (Loan loan in loans)
{
loan.PayFine();
}
}
}
// Generalization: a Librarian is a Member and adds an employee id
public class Librarian : Member
{
public Librarian(string name, Library library, string employeeId)
: base(name, library)
{
EmployeeId = employeeId;
}
public string EmployeeId { get; }
}
public static class LibraryDemo
{
private static string Dollars(int cents) => $"${cents / 100}.{cents % 100:D2}";
public static void Main()
{
var library = new Library();
var cleanCode = new Book("Clean Code", "Robert C. Martin", "978-0132350884");
library.Add(cleanCode);
library.Add(new Book("Refactoring", "Martin Fowler", "978-0134757599"));
foreach (Book book in library.Search("martin"))
{
Console.WriteLine($"Found: {book.Title}");
}
var alice = new Member("Alice", library);
var bob = new Librarian("Bob", library, "E-101");
Loan loan = alice.Borrow("978-0132350884", 2);
Console.WriteLine($"{alice.Name} borrowed Clean Code on day 2, "
+ $"due back on day {loan.DueDay}");
try
{
bob.Borrow("978-0132350884", 3);
}
catch (InvalidOperationException e)
{
Console.WriteLine(
$"{bob.Name} ({bob.EmployeeId}) is turned away: {e.Message}");
}
loan.GiveBack(19);
Console.WriteLine($"Back on day 19, the book is {cleanCode.Status} and "
+ $"{alice.Name} owes {Dollars(alice.Owes())}");
alice.PayFines();
Console.WriteLine($"After paying, {alice.Name} owes {Dollars(alice.Owes())}");
}
}package main
import (
"fmt"
"strings"
)
// «enumeration» BookStatus: Go has no enum, so a string type and its constants
type BookStatus string
const (
Available BookStatus = "AVAILABLE"
Borrowed BookStatus = "BORROWED"
Reserved BookStatus = "RESERVED"
Lost BookStatus = "LOST"
)
// «interface» Searchable: a Go interface
type Searchable interface {
Search(query string) []*Book // Book [*]: any number of books, so a slice
}
// Go hides a name by starting it with a small letter:
// these fields are private to the package
type Book struct {
title string
author string
isbn string
status BookStatus // - status: BookStatus
}
func NewBook(title, author, isbn string) *Book {
return &Book{title: title, author: author, isbn: isbn, status: Available}
}
func (b *Book) Title() string { return b.title }
func (b *Book) ISBN() string { return b.isbn }
func (b *Book) Status() BookStatus { return b.status }
func (b *Book) IsAvailable() bool { return b.status == Available }
func (b *Book) MarkAsBorrowed() { b.status = Borrowed }
func (b *Book) MarkAsReturned() { b.status = Available }
func (b *Book) Matches(query string) bool {
q := strings.ToLower(query)
return strings.Contains(strings.ToLower(b.title), q) ||
strings.Contains(strings.ToLower(b.author), q)
}
// Composition: a Fine is made by one Loan and lives inside it
type Fine struct {
cents int
paid bool
}
func (f *Fine) Due() int {
if f.paid {
return 0
}
return f.cents
}
func (f *Fine) Pay() { f.paid = true }
const (
loanDays = 14 // a package constant: static, so underlined in the diagram
dailyFine = 50 // cents for each day late
)
type Loan struct {
book *Book // - book, multiplicity 1: one pointer
dueDay int
fine *Fine // - fine, multiplicity 0..1: nil until a late return
}
func NewLoan(book *Book, day int) *Loan {
return &Loan{book: book, dueDay: day + loanDays}
}
func (l *Loan) DueDay() int { return l.dueDay }
func (l *Loan) GiveBack(day int) {
l.book.MarkAsReturned()
if daysLate := day - l.dueDay; daysLate > 0 {
l.fine = &Fine{cents: daysLate * dailyFine} // the loan makes its own fine
}
}
func (l *Loan) FineDue() int {
if l.fine == nil {
return 0
}
return l.fine.Due()
}
func (l *Loan) PayFine() {
if l.fine != nil {
l.fine.Pay()
}
}
// Realization: Library has Search, so it satisfies Searchable;
// the var line below makes the compiler check it
type Library struct {
books []*Book // - books, multiplicity *: books made elsewhere (aggregation)
}
var _ Searchable = (*Library)(nil)
func (lib *Library) Add(book *Book) { lib.books = append(lib.books, book) }
func (lib *Library) Search(query string) []*Book {
var found []*Book
for _, book := range lib.books {
if book.Matches(query) {
found = append(found, book)
}
}
return found
}
// «Create»: the library makes a Loan and hands it over without keeping it.
// Go returns an error as a second value where Java throws.
func (lib *Library) Lend(isbn string, day int) (*Loan, error) {
for _, book := range lib.books {
if book.ISBN() == isbn {
if !book.IsAvailable() {
return nil, fmt.Errorf("%s is %s", book.Title(), book.Status())
}
book.MarkAsBorrowed()
return NewLoan(book, day), nil
}
}
return nil, fmt.Errorf("no book with ISBN %s", isbn)
}
type Member struct {
name string
library *Library // - library, multiplicity 1
loans []*Loan // - loans, multiplicity *
}
func NewMember(name string, library *Library) *Member {
return &Member{name: name, library: library}
}
func (m *Member) Name() string { return m.name }
func (m *Member) Borrow(isbn string, day int) (*Loan, error) {
loan, err := m.library.Lend(isbn, day)
if err != nil {
return nil, err
}
m.loans = append(m.loans, loan)
return loan, nil
}
func (m *Member) Owes() int {
total := 0
for _, loan := range m.loans {
total += loan.FineDue()
}
return total
}
func (m *Member) PayFines() {
for _, loan := range m.loans {
loan.PayFine()
}
}
// Generalization: Go has no inheritance, so a Librarian embeds a Member
// and gets its methods
type Librarian struct {
*Member
employeeID string
}
func NewLibrarian(name string, library *Library, employeeID string) *Librarian {
return &Librarian{Member: NewMember(name, library), employeeID: employeeID}
}
func (l *Librarian) EmployeeID() string { return l.employeeID }
func dollars(cents int) string {
return fmt.Sprintf("$%d.%02d", cents/100, cents%100)
}
func main() {
library := &Library{}
cleanCode := NewBook("Clean Code", "Robert C. Martin", "978-0132350884")
library.Add(cleanCode)
library.Add(NewBook("Refactoring", "Martin Fowler", "978-0134757599"))
for _, book := range library.Search("martin") {
fmt.Println("Found: " + book.Title())
}
alice := NewMember("Alice", library)
bob := NewLibrarian("Bob", library, "E-101")
loan, err := alice.Borrow("978-0132350884", 2)
if err != nil {
panic(err)
}
fmt.Printf("%s borrowed Clean Code on day 2, due back on day %d\n",
alice.Name(), loan.DueDay())
if _, err := bob.Borrow("978-0132350884", 3); err != nil {
fmt.Printf("%s (%s) is turned away: %v\n", bob.Name(), bob.EmployeeID(), err)
}
loan.GiveBack(19)
fmt.Printf("Back on day 19, the book is %s and %s owes %s\n",
cleanCode.Status(), alice.Name(), dollars(alice.Owes()))
alice.PayFines()
fmt.Printf("After paying, %s owes %s\n", alice.Name(), dollars(alice.Owes()))
}It prints:
Found: Clean Code
Found: Refactoring
Alice borrowed Clean Code on day 2, due back on day 16
Bob (E-101) is turned away: Clean Code is BORROWED
Back on day 19, the book is AVAILABLE and Alice owes $1.50
After paying, Alice owes $0.00
The book went out on day 2, so it was due back on day 16. It came back on day 19, 3 days late, and at 50 cents a day the loan made a fine of 150 cents.
Each part of the diagram turns into code in the same way every time:
- A box becomes a class. «interface» becomes an interface (an abstract class in Python and C++), and «enumeration» becomes an enum (in Go, a string type with constants).
- An attribute becomes a field with the same name.
-makes a member private and+makes it public. - A line with an arrowhead becomes a field in the class it starts from, named after the far end:
- loansis theloansfield ofMember. The multiplicity picks the field's shape.1is a single reference set when the object is made,*is a list, and0..1is a reference that may be empty, which is whyfinestarts out empty (null, orNonein Python andnilin Go). - A filled diamond means the whole makes the part itself and never hands it out. Only
Loanmakes aFine, and C++ says so in the field's type, aunique_ptrthat owns it. - A hollow diamond means the parts arrive from outside:
Librarykeeps books it was given. - A hollow triangle becomes
extendson a solid line andimplementson a dashed one. Go has neither, so itsLibrarianembeds aMember, and itsLibrarysatisfiesSearchableby having aSearchmethod. - A dashed «Create» arrow becomes a method that makes an object and returns it, as
lenddoes, with no field to keep it.
Each language also keeps its own habits, noted in the comments: C# writes getters as properties (Title), Go returns an error as a second value where Java throws an exception, and Python marks private names with a leading underscore.
Common Mistakes When Drawing Class Diagrams
Mistake 1: a filled diamond for every kind of having. Member keeps a list of Loan objects, so a filled diamond looks right at first. But the library makes each loan and the member hands it straight back to its caller, so other code holds the same loan, and that makes it an association. Composition needs a part that its whole makes and keeps to itself, as Fine inside Loan. Ask who makes the part and who else can reach it.
Mistake 2: every field and method. A box that lists every getter, setter, toString and equals buries the design under detail. Show the members that explain what each class is for. UML even lets a list end with three dots to say that more exist: "an ellipsis (...) as the final element of a list of Features may be used to indicate that additional Features exist but are not shown in that list." The library's diagram shows every member only because its classes are small.
Mistake 3: lines with no numbers. A line from Member to Loan with nothing at its ends leaves the reader guessing whether a member has one loan or a hundred, and UML gives them nothing to guess from: "If no multiplicity is shown on the diagram, no conclusion may be drawn about the multiplicity in the model." Put the numbers on every end a reader needs. They decide the code too, a single reference for 1 and a list for *.
Mistake 4: the same line for a subclass and for an interface. Both end in a hollow triangle, and only the line tells them apart: solid from Librarian to Member, dashed from Library to Searchable. The dashed line says a class keeps the promise an interface makes. The solid one says a class takes over its parent's fields and code.
Mistake 5: a dashed arrow for a field. Dependency — Objects That Use Each Other draws a dashed arrow for a use that lasts one call: a parameter, a local variable, a returned object. A field is a lasting link. Book keeps its status in a field, so the diagram writes BookStatus as the type of an attribute and draws no arrow to it.
Mistake 6: details that only the code needs. A private cache map or a helper method that checks an ISBN's digits tells the reader nothing about the design. Leave them to the code, and draw them only when the design depends on them.
Practice Tips
Start from the requirements and underline the nouns, because they are the candidate classes. For the library they give a book, a member, a librarian, a loan, a fine and the library itself. The Object Discovery Process — Nouns, Verbs, Relationships takes this method further.
Then add the lines. For each pair of classes, ask whether one keeps the other in a field, whether one is a kind of the other, and whether one only uses the other for a moment. For a part, ask who makes it and whether anything else can reach it, which decides between the two diamonds.
Keep each diagram small enough to read at a glance. When a system grows, draw several diagrams, one for each area of it, and place linked classes next to each other so that few lines cross.
In an interview, a quick sketch is usually what is wanted. Hello Interview's guide puts it this way: "A simple list of entities and a few arrows showing which objects own or use which others is more than enough." The notation on this page is what lets anyone who knows UML read that sketch the way you meant it.
Use Case Diagrams — Who Does What turns from the structure of the library to the people who use it.
Key Takeaways
- A class box has three compartments, the name, the attributes and the operations, and each member is written with its visibility (
+,-,#or~) and its type. - Solid or dashed, and the shape at the end, tell the six relationships apart: association, aggregation (hollow diamond), composition (filled diamond), generalization (solid line, hollow triangle), realization (dashed line, hollow triangle) and dependency (dashed arrow).
- The multiplicity at each end of a line says how many objects take part, and it decides the code: one reference, an optional one, or a list.
- Every box and line maps to code: a class, a field named after the line's end,
extendsorimplements, or a method that makes an object.