Class design
Class design: principles, UML notation, responsibilities, relationships (association/aggregation/composition/inheritance), and practical examples for designing well-formed classes and class diagrams.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Class design is used by engineers when they convert requirements into stable, testable code modules and UML class diagrams. Good class design improves maintainability, reduces bugs, and makes systems easier to extend — important for exams, project work, and industry code reviews.
Key ideas
Start from first principles and simple definitions: define every term before using it.
- Class — a blueprint that defines a set of attributes (data) and methods (operations). Use: to describe the static structure of objects in a system. (Assumption: a class groups related data and behaviour.)
- Object — a runtime instance of a class with concrete values for attributes. (Assumption: objects have identity and state.)
- Attribute — a named data item of a class (also called a property or field). Define its type and visibility.
- Method — a named operation of a class; may have parameters, return type, and visibility.
- Encapsulation — bundling attributes and methods and restricting direct access to some of an object's components. (Assumption: use visibility to protect invariants.)
- Visibility — access control for attributes/methods: common symbols are
+(public),-(private),#(protected),~(package). Use these to enforce encapsulation. - Association — a structural relationship where objects of one class are connected to objects of another. Represented by a solid line in UML. Multiplicity indicates how many instances relate.
- Aggregation — a weak “whole-part” relationship. In UML draw an open (white) diamond at the whole end. Parts can exist independently of the whole. (Assumption: lifetime of parts is independent.)
- Composition — a strong “whole-part” relationship. In UML draw a filled (black) diamond at the whole end. Parts’ lifetime is bound to the whole; if whole is destroyed, parts are destroyed. (Assumption: ownership and lifetime binding.)
- Inheritance (Generalisation) — a relationship where a class (subclass) inherits attributes and methods from a parent (superclass). UML uses a solid line with a hollow triangle pointing to the superclass. (Assumption: subtype should behave as its supertype.)
- Interface — a named set of method signatures (no implementation in many languages). Realisation is the relationship where a class implements an interface (UML: dashed line with hollow triangle).
- Abstract class — a class that cannot be instantiated and may have abstract methods that subclasses must implement.
- Cohesion — a measure of how closely related the responsibilities of a single class are. High cohesion means one well-focused responsibility. (Assumption: classes should aim for high cohesion.)
- Coupling — a measure of how much one class depends on another. Low coupling is desirable.
- Responsibility — a reason for a class to exist; responsibilities include maintaining state, performing calculations, coordinating other objects.
Design principles frequently used by engineers (state exactly):
- Single Responsibility Principle (SRP) — A class should have only one reason to change; formally: each class should have one responsibility or axis of change.
- Open-Closed Principle (OCP) — Software entities (classes, modules) should be open for extension but closed for modification. (Assumption: design extension via inheritance or composition and polymorphism.)
- Liskov Substitution Principle (LSP) — If S is a subtype of T, then objects of type T may be replaced with objects of type S without altering desirable program properties (correctness, task performed). Universities expect this exact statement and an example showing pre/postconditions preserved by a subtype. Example: If
BankAccount.withdrawhas preconditionamount > 0and postcondition that the balance never goes below zero, thenSavingsAccount.withdrawmust not strengthen the precondition (e.g., by requiringamount >= 100) and must preserve the postcondition. - Interface Segregation Principle (ISP) — Clients should not be forced to depend on interfaces they do not use; prefer many small, specific interfaces rather than a large, general interface.
- Dependency Inversion Principle (DIP) — High-level modules should not depend on low-level modules; both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions.
UML notation specifics to state for exam diagrams (draw exactly as described):
- Draw a class as a rectangle split into three horizontal compartments: top for ClassName (centered, italicize if abstract or add {abstract}), middle for attributes (each on its own line: visibility name : type), bottom for methods (visibility name(parameter-list) : return-type).
- Use
+for public,-for private,#for protected,~for package. - For association draw a solid line; label role names near the line ends and multiplicities next to each end (e.g.,
1,0..*,1..*). Add an arrow for navigability if only one direction. - For aggregation draw a solid line with an open diamond at the whole side.
- For composition draw a solid line with a filled diamond at the whole side.
- For inheritance draw a solid line with a hollow triangle at the superclass side.
- For dependency draw a dashed arrow from client to supplier.
Step-by-step derivation universities often ask for: deriving multiplicity from requirement text. Example method:
- Identify nouns (candidate classes/objects) and verbs (candidate operations) from the requirement.
- For each relationship phrase ("each A has many B"), map to multiplicity: "many" →
0..*or1..*depending on whether B can be absent. - Decide ownership: if text says "A creates and destroys B" choose composition; if B exists independently choose aggregation.
Formulas (syntax to remember)
class ClassName { — start of a class body (language-neutral example)
+ attributeName : Type — public attribute (UML attribute notation)
- attributeName : Type — private attribute (UML attribute notation)
+ methodName(params) : ReturnType — public method (UML operation notation)
Java class skeleton:
public class ClassName {
private Type attr;
public ReturnType methodName(ParamType p) { ... }
}
C++ class skeleton:
class ClassName {
public:
ReturnType methodName(ParamType p);
private:
Type attr;
};
Python class skeleton:
class ClassName:
def __init__(self, p: ParamType):
self._attr = p
def method_name(self, p: ParamType) -> ReturnType:
...
UML visibility symbols to remember: +, -, #, ~ (as defined above).
Worked examples
Example 1 — Bank account class (exam-style model answer) Requirement (short): "A BankAccount has an account number, balance, and supports deposit(amount) and withdraw(amount). Withdraw must not allow negative balance; interest calculation is done by subclasses." Design steps:
- Identify class: BankAccount. Attributes:
accountNumber : String,balance : Money. - Methods:
deposit(amount : Money) : void,withdraw(amount : Money) : boolean,getBalance() : Money,calculateInterest() : Money(abstract). - Decide visibility: attributes
- accountNumber,- balance; methods+exceptcalculateInterestis#or abstract+but declared abstract. - Invariants and pre/postconditions for exams: precondition for
deposit:amount > 0; postcondition:balance_post = balance_pre + amount. Forwithdraw: preconditionamount > 0; postconditions: ifamount <= balance_prethenbalance_post = balance_pre - amountand returntrue; otherwisebalance_post = balance_preand returnfalse. - UML drawing instructions: draw a rectangle with three compartments.
- Top: write
BankAccount(italicize if abstract class or add{abstract}). - Middle (attributes):
- accountNumber : String,- balance : Money - Bottom (methods):
+ deposit(amount : Money) : void,+ withdraw(amount : Money) : boolean,+ getBalance() : Money,# calculateInterest() : Money {abstract}
- Top: write
- Note on extension: create subclasses
SavingsAccountandCheckingAccountinheriting fromBankAccountand implementcalculateInterest(). Final answer should state why each visibility and pre/postcondition was chosen.
Example 2 — Library Book and Member (showing association, aggregation, composition) Requirement (short): "Library has many Books; Members borrow Books. A Copy cannot exist without a Library, and a Book has multiple copies." Design steps:
- Candidate classes: Library, Book, Copy, Member.
- Ownership decisions:
- A
Copyis a physical copy owned byLibrary: choose composition between Library (whole) and Copy (part) because copies are created and removed by the Library. Book(title, author) is an abstract concept:Librarymay have an aggregation relationship toBook(library references book metadata but metadata can exist without a particular library).MemberborrowsCopy: associationMember0..* ↔ 0..*Copywith a borrow date and return date (association classLoan).
- A
- UML drawing instructions:
- Draw classes
Library,Book,Copy,Member,Loanas rectangles with attributes/methods. - Draw a filled diamond from
LibrarytoCopywith multiplicity1at Library end and0..*at Copy end. - Draw an open diamond from
LibrarytoBookwith multiplicity0..*at Book end and0..*at Library end. - Draw a solid line between
MemberandCopy. Near the line, write multiplicities:Memberend0..*,Copyend0..*. If model requires a loan date, use an association class namedLoanattached to the association line.
- Draw classes
- State reasons for composition vs aggregation as part of the exam answer.
Common mistakes
- Violating LSP by making subclass strengthen preconditions or weaken postconditions. Always check pre/postconditions when using inheritance.
- Overloading a class with unrelated responsibilities (violates SRP); leads to low cohesion.
- Writing multiplicities wrong from requirements (e.g., writing
1when requirement allows zero instances). - Not using interfaces/abstract classes when multiple implementations are required (violates DIP/OCP).
For your exam
Question types you will see: definitions (short), draw-and-label UML class diagrams, derive multiplicities from requirement text, design a class with attributes/methods and pre/postconditions, compare aggregation vs composition, apply SOLID principles in a short note. What a full-marks answer includes:
- Clear definitions of the requested terms (use the exact terms above).
- A neat UML diagram drawn as described (three compartments, visibility symbols, correct relationship symbols, multiplicities and role names).
- For design questions: list attributes and methods with visibility, state preconditions/postconditions for important methods and class invariants, justify choices of aggregation/composition/inheritance, and mention which SOLID principles influenced your decisions.
Quick check
- What UML symbol shows composition?
- State the Single Responsibility Principle in one sentence.
- Give the precondition and postcondition for a deposit(amount) method on a BankAccount. Answers: 1) A filled (black) diamond at the whole end. 2) A class should have only one reason to change (one responsibility). 3) Precondition: amount > 0; Postcondition: balance_post = balance_pre + amount.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?