CLASS DIAGRAMS

Class Relationships Cheat Sheet

Mastering Association, Aggregation, Composition, and Inheritance with UML syntax and code.

Structural

Association

A loose relationship where objects have their own lifecycle and there is no ownership. 'Uses-A' or 'Knows-A'.

class Teacher { ... }
class Student { ... }
// Association: Both exist independently
class Course {
void enroll(Student s, Teacher t) {
// Uses student and teacher
}
}
Has-A (Weak)

Aggregation

A 'Has-A' relationship where the child can exist independently of the parent. Weak ownership.

class Department {
private List<Teacher> teachers; // Has-A
// Teachers exist outside Department
Department(List<Teacher> t) {
this.teachers = t;
}
}
Has-A (Strong)

Composition

Strong 'Has-A'. The child cannot exist without the parent. If parent is destroyed, child is too.

class House {
private final List<Room> rooms;
House() {
// Rooms created INSIDE House
this.rooms = new ArrayList<>();
rooms.add(new Room("Kitchen"));
}
}
Is-A

Inheritance

An 'Is-A' relationship. The child class inherits fields and methods from the parent.

class Vehicle { ... }
// Car IS-A Vehicle
class Car extends Vehicle {
void drive() { ... }
}
Uses-A

Dependency

A weaker form of association where one class depends on another temporarily (e.g., method parameter).

class Logger {
void log(String msg) { ... }
}
class User {
// User depends on Logger temporarily
void login(Logger logger) {
logger.log("Login success");
}
}
Contract

Realization (Impl)

A class implements an interface. It promises to fulfill the contract defined by the interface.

interface Playable {
void play();
}
class Guitar implements Playable {
public void play() {
System.out.println("Strumming");
}
}
Pattern

Delegation

Passing responsibility to another object. Alternative to inheritance ('Composition over Inheritance').

class Printer {
void print() { System.out.println("Printing"); }
}
class Office {
private Printer p = new Printer();
// Delegate print task
void printDoc() { p.print(); }
}