Home
8UML Class Diagrams
8

Topic 8 of 9 · Labs IX–X

UML Class Diagrams

Classes, attributes, operations and visibility; association, multiplicity, aggregation, composition and dependency; generalization, abstract classes, interfaces and realization, with the telephone and ATM examples.

← → move between slides · F full screen · M slide list

Before we start

Why this matters

Your sequence diagrams are full of messages: verifyPIN(), withdraw(), debit(). Which class owns each one, and what does each class need to remember?

The class diagram is the blueprint programmers turn into code and database tables. It is where all the earlier models meet: nouns from the SRS become classes, messages from sequence diagrams become operations.

This topic covers both labs: the basic class diagram (Lab IX) and the extended one with inheritance, abstract classes and interfaces (Lab X).

Outline · Labs IX–X

Topics in this chapter

Select a topic to jump to the slide that explains it.

  1. Class diagram basics
  2. Relationships
  3. Extended class diagrams
  4. Worked diagrams
  5. Designing your own
  6. Common mistakes

Concept 1 of 15

UML and the class diagram

UML (Unified Modeling Language) is the standard visual language for the architecture, design and implementation of software. Its diagrams fall into two families:

Structural (static)Behavioural (dynamic)
Class, object, component, deployment, packageuse case, sequence, communication, activity, state machine

A class diagram shows the classes of a system, their attributes and operations, and the relationships between them. It is the most used UML diagram and the only one that maps almost one-to-one onto code.

  • Describes the static view of the system.
  • Models how the elements of that view collaborate.
  • Describes the functions the system performs through its operations.
  • Is the blueprint for object-oriented code (Java, C#, Python) and for the database design.
  • Supports forward engineering (diagram → code) and reverse engineering (code → diagram).

Class diagram basics

Anatomy of a class

Three compartments: name, attributes, operations.

Class diagram basics

Anatomy of a class (cont.)

  • Name: centred, bold, starts with a capital letter, singular noun (Account, not Accounts).
  • Attributes: left-aligned, first letter lowercase, one per line: visibility name : type = default, e.g. - balance : double = 0.
  • Operations: visibility name(parameter : type) : returnType, e.g. + withdraw(amount : double) : boolean.
  • The attribute and operation compartments are optional; an empty box with only a name is fine in an overview diagram.

Class diagram basics

Visibility and other markers

SymbolVisibilityWho can access it
+publicany class
-privateonly this class
#protectedthis class and its subclasses
~packageclasses in the same package
MarkerMeaning
underlinedstatic (class-level) member
italic nameabstract class or operation
/ namederived attribute (calculated, e.g. /age)
{readOnly}cannot change after creation
«interface»stereotype on an interface
Rule of thumb: attributes are private (-) and accessed through public operations (+) — that is encapsulation, from your OOP course.

Class diagram basics

Visibility and other markers (cont.)

Concept 4 of 15

Relationships at a glance

From the weakest link (dependency) to the strongest (composition), plus inheritance and realization.

Concept 4 of 15

Relationships at a glance (cont.)

RelationshipNotation
Associationsolid line (open arrow if one-way)
Inheritance (generalization)solid line, hollow triangle at the parent
Realization / implementationdashed line, hollow triangle at the interface
Dependencydashed line, open arrow
Aggregationsolid line, hollow diamond at the whole
Compositionsolid line, filled diamond at the whole

The lab manual’s Table X.1, in words.

Relationships

Association and multiplicity

  • An association is a lasting structural link: objects of one class hold references to objects of the other.
  • Bidirectional (plain line): both classes know each other. Unidirectional (open arrow): only the source knows the target.
  • Label it with a name (a verb: owns) and optionally role names at the ends.
  • Multiplicity at each end says how many objects take part: 1, 0..1, *, 1..*, 2..4.
  • Read multiplicity from the far end: “one Company employs 1..* Employees; each Employee works for 1 Company.”

Relationships

Association and multiplicity (cont.)

Multiplicity values.

Interactive

Reading multiplicity

Relationships

Aggregation, composition and dependency

Aggregation ◇Composition ◆Dependency ⇢
Meaningwhole–part, “has a”strong whole–part, “owns / is made of”“uses” for a short time
Part’s lifetimeindependent of the wholeends with the wholeno lasting link
Can a part be shared?yesno — one whole only—
ExampleDepartment ◇— Teacher; College ◇— StudentHouse ◆— Room; Order ◆— OrderLineStudent ⇢ College (a method parameter)
In codethe whole keeps references passed in from outsidethe whole creates and owns its partsa parameter, local variable or return type

Relationships

Aggregation, composition and dependency (cont.)

Java code
class House {                       // composition
    private List<Room> rooms = new ArrayList<>();
    House() { rooms.add(new Room("Kitchen")); }   // parts created inside
}
class Department {                  // aggregation
    private List<Teacher> teachers;
    void add(Teacher t) { teachers.add(t); }       // parts come from outside
}
Output · as a UML class diagram
UML for the code: House with a filled diamond to Room (1 to 1..*), Department with a hollow diamond to Teacher (many)

Java prints nothing for class declarations; what this code means is the diagram above.

If you delete the House, its Rooms go too (composition). If a Department closes, the Teachers still exist (aggregation). When in doubt, use a plain association — it is never wrong, only less precise.

Concept 8 of 15

Generalization and abstract classes

Person is abstract; Employee and Customer inherit and implement printInfo().

Concept 8 of 15

Generalization and abstract classes (cont.)

Java code
abstract class Person {
    private String name, address;
    abstract void printInfo();
}
class Employee extends Person { ... }
Output · as a UML class diagram
No console output: these lines only declare classes. In UML they are the figure above: Person in italics (abstract) with - name, - address and the italic printInfo(), and Employee joined to it by a hollow-triangle arrow (extends).
  • Generalization is inheritance: the child is a kind of the parent and inherits its attributes and operations. Draw a solid line with a hollow triangle pointing to the parent.
  • An abstract class cannot be instantiated; its name is written in italics (or marked {abstract}).
  • An abstract operation has no body; it is also italic, and each concrete subclass must implement it.
  • Draw one triangle and merge the lines when several classes share a parent.

Extended class diagrams

Interfaces and realization

DebitCard and MobileWallet both realize Payable.

Extended class diagrams

Interfaces and realization (cont.)

Java code
interface Payable {
    boolean pay(double amount);
    void refund(String id);
}
class DebitCard implements Payable { ... }
Output · as a UML class diagram
No console output: these lines only declare types. In UML they are the figure above: a box marked «interface» Payable with + pay(amount : double) : boolean and + refund(id : String) : void, and DebitCard joined to it by a dashed hollow-triangle arrow (implements).
  • An interface is a named set of operations with no implementation — a contract. Show it as a class box with «interface» above the name.
  • Realization (implementation): a dashed line with a hollow triangle from the class to the interface. The class promises to implement every operation.
  • A class can realize many interfaces but (in Java) extend only one class.
  • Example from the manual: an Owner interface with acquire(property) and dispose(property), realized by both Person and Corporation — in very different ways.

Interactive

Name the relationship

Concept 11 of 15

Example: a telephone

The telephone example from the lab manual (Figure IX.8).

Concept 11 of 15

Example: a telephone (cont.)

  • A Telephone aggregates a Ringer, a CallerId and an AnsweringMachine (hollow diamonds at Telephone).
  • The AnsweringMachine is composed of its recorded Messages (filled diamond): delete the machine and the messages go with it.
  • A Line connects 0..* telephones; each telephone is on 0..1 line.
  • Every attribute is private (-) with public operations (+).

Worked diagrams

Example: the ATM system

Worked diagrams

Example: the ATM system (cont.)

Redrawn from the manual’s Figure X.6. The two inheritance trees (accounts and transactions) and the multiplicities are the parts examiners check first.

Concept 13 of 15

How to design a class diagram

  1. Identify the classes. Underline the nouns in the SRS and use case descriptions; keep the ones the system must remember (Account, Card), drop synonyms, attributes (balance) and actors that are outside the system.
  2. Add attributes — facts about each class (name, address, dob).
  3. Add operations — the verbs, and every message from your sequence diagrams.
  4. Find relationships: “has / owns” → association or aggregation/composition; “is a kind of” → generalization; “implements” → realization; “uses briefly” → dependency.

Concept 13 of 15

How to design a class diagram (cont.)

  1. Add multiplicities at both ends of every association.
  2. Review against the use cases: can every scenario be carried out with these classes?

Noun analysis on the ATM description

“A customer inserts a debit card into the ATM. The bank checks the PIN and the balance of the account. Each transaction — a withdrawal or transfer — is recorded with its date.”

Classes: Customer, DebitCard, ATM, Bank, Account, ATMTransaction, Withdrawal, Transfer. Attributes: PIN (of card), balance (of account), date (of transaction).

Concept 14 of 15

Common mistakes

MistakeFix
Plural class names (Students)singular: Student
Actors or the whole system drawn as classes (“ATMSystem”, “User interface”)model the domain objects instead
Attributes that are really other classes (account : String in Customer)draw an association to Account
Associations without multiplicityadd it at both ends
Composition used for everythingcomposition only when parts die with the whole
Triangle pointing to the childit points to the parent
Operations with no parameters or typeswrite withdraw(amount : double) : boolean
Class diagram and sequence diagram disagreeevery message ↔ an operation of the receiver

Your turn

Your turn: the lab tasks

Student Registration System (Lab IX)

The manual says it must include students, courses, registration, payment, requirements and transactions; a semester contains courses; courses can be registered, dropped, withdrawn, passed or failed; semesters can be frozen or attended; there are undergraduate (BCS, MCS) and postgraduate (MPhil, PhD) students who enrol in different ways.

  • Which sentence suggests generalization?
  • Is Semester–Course aggregation or composition? Defend it.
  • Where do the verbs (register, drop, withdraw…) become operations?
  • Which multiplicities apply between Student, Registration and Course?

Library Management System (Lab X)

  • Candidate classes come from the nouns: user/member (student, staff), librarian, library card, book, reservation, loan, fine, feedback.
  • Which are kinds of something else?
  • Does a Fine exist without a Loan?
  • Use your sequence diagrams: every message must appear as an operation.
Draw and submit your own diagrams; the questions are prompts, not answers.

Worked example 1 of 3

Worked example 1

Draw the UML for this Java class: public class Book { private String isbn; private String title; private static int count; public boolean isAvailable() { … } }
Show the solution
Class box Book. Attributes: - isbn : String, - title : String, - count : int (underlined, because static). Operation: + isAvailable() : boolean.

Worked example 2 of 3

Worked example 2

A Library has many Books; a Book belongs to one Library. A Book can exist in a donation list before it joins a library. Which relationship and multiplicities?
Show the solution
Aggregation (hollow diamond at Library): the book can exist without the library. Library end 0..1 (a donated book has no library yet), Book end 0..*.

Worked example 3 of 3

Worked example 3

SavingsAccount and CurrentAccount both have accountNo and balance and both implement calculateInterest() differently. Model it.
Show the solution
An abstract class Account with - accountNo : String, - balance : double and the abstract operation + calculateInterest() : double. SavingsAccount and CurrentAccount each generalize to Account (hollow triangle at Account) and implement calculateInterest().

Practice

Practice (1 of 2)

Try each one on paper first, then check your answer.

1. What do +, -, # and ~ mean in front of an attribute?
Show the answer
public, private, protected and package visibility.
2. Write the UML operation for a Java method public double getBalance().
Show the answer
+ getBalance() : double
3. What is the difference between aggregation and composition? Give one example of each.
Show the answer
In aggregation the part can exist independently (Department–Teacher); in composition the part is owned by exactly one whole and is destroyed with it (House–Room).

Practice

Practice (2 of 2)

Try each one on paper first, then check your answer.

4. How is an abstract class shown in UML?
Show the answer
Its name is written in italics (or marked {abstract}); abstract operations are italic too.
5. Lab task hint: which classes in the Student Registration System form an inheritance hierarchy?
Show the answer
Student is the parent of UndergraduateStudent and PostgraduateStudent, because they are kinds of student that enrol in different ways (possibly an abstract enroll() operation).
6. Read aloud: Customer 1 —— owns —— 1..* Account.
Show the answer
Each customer owns one or more accounts; each account is owned by exactly one customer.

Check yourself

Quiz

Resources

Further learning (cont.)

ToolMermaid: class diagrams ↗Class diagrams in Markdown; renders on GitHub.ToolStarUML ↗Desktop UML tool with code generation for Java and C#.ArticleClass diagram ↗Overview of elements and relationships.StandardOMG UML specification ↗The official definition of every symbol.
BookUML Distilled, 3rd ed. — Martin FowlerAddison-Wesley, 2003. Chapters 3 and 5 cover class diagrams, basic and advanced.
BookApplying UML and Patterns, 3rd ed. — Craig LarmanPrentice Hall, 2004. How to find classes from use cases and assign responsibilities.

Summary

Summary

  • A class box has name, attributes (visibility name : type) and operations (visibility name(params) : type).
  • Visibility: + public, - private, # protected, ~ package; underline = static, italic = abstract.
  • Association (with multiplicity) < aggregation (◇, independent parts) < composition (◆, parts die with the whole); dependency is a short “uses”.
  • Generalization (hollow triangle to the parent) = inheritance; realization (dashed) = implementing an interface.
  • Find classes from nouns, operations from verbs and sequence-diagram messages.
  • Check the class diagram against the use cases and sequence diagrams.