In Inheritance we connected classes with an "is-a" relationship: a Dog is an Animal. But most connections in real programs are not "is-a" at all. A teacher teaches students. A department has professors. A house is made of rooms. These are "has-a" (or "uses-a") relationships, and object-oriented design names three flavours of them: association, aggregation and composition.
The three differ in one key question: how strongly are the two objects' lives tied together?
Association: two classes are related and their objects know about each other, but each lives independently. Aggregation: a special association where one object is a "whole" that groups "parts", but the parts can exist without it and may be shared. Composition: a strong aggregation where the part belongs to exactly one whole and cannot outlive it.
weakest link strongest link
Association ──► Aggregation ──► Composition
"knows / uses" "has (shares)" "owns / is made of"
Teacher ── Student Department ◇── Professor House ◆── RoomComposition is a kind of aggregation, and aggregation is a kind of association. So every composition is also an association, but not the other way round.
Association: Objects That Know Each Other
An association simply means objects of one class hold references to objects of another class (or call them) as part of their normal job. Neither one owns the other. If a teacher leaves the college, students do not vanish, and vice versa.
Two properties describe an association:
Direction: unidirectional (only A knows B, e.g. an
Orderknows itsCustomerbut the customer object does not list orders) or bidirectional (both know each other).Multiplicity (cardinality): how many objects on each side. Written as
1,0..1,*(zero or more),1..*(one or more). This is the same idea as cardinality in ER diagrams.
┌─────────┐ * * ┌─────────┐
│ Teacher │──────────────────│ Student │ many-to-many, bidirectional
└─────────┘ teaches └─────────┘Here is a bidirectional many-to-many association. The tricky part of bidirectional links is keeping both sides consistent, so each side's "add" method also updates the other side (with a check to stop infinite recursion).
import java.util.ArrayList;
import java.util.List;
class Teacher {
private final String name;
private final List<Student> students = new ArrayList<>();
Teacher(String name) { this.name = name; }
String getName() { return name; }
void teach(Student s) { // keeps BOTH sides of the link in sync
if (!students.contains(s)) {
students.add(s);
s.addTeacher(this);
}
}
void printStudents() {
System.out.print(name + " teaches:");
for (Student s : students) System.out.print(" " + s.getName());
System.out.println();
}
}
class Student {
private final String name;
private final List<Teacher> teachers = new ArrayList<>();
Student(String name) { this.name = name; }
String getName() { return name; }
void addTeacher(Teacher t) {
if (!teachers.contains(t)) {
teachers.add(t);
t.teach(this);
}
}
void printTeachers() {
System.out.print(name + " learns from:");
for (Teacher t : teachers) System.out.print(" " + t.getName());
System.out.println();
}
}
public class AssociationDemo {
public static void main(String[] args) {
Teacher rao = new Teacher("Rao"), sen = new Teacher("Sen");
Student asha = new Student("Asha"), ravi = new Student("Ravi");
rao.teach(asha);
rao.teach(ravi);
asha.addTeacher(sen); // works from either side
rao.printStudents();
sen.printStudents();
asha.printTeachers();
ravi.printTeachers();
}
}Output:
Rao teaches: Asha Ravi
Sen teaches: Asha
Asha learns from: Rao Sen
Ravi learns from: RaoNotice that teachers and students are created independently in main, and linking them changes neither one's existence. That is the mark of a plain association.
Design tip: prefer unidirectional associations when you can. Every bidirectional link is two references that must be kept in sync, and it makes the two classes depend on each other.
Aggregation: A Whole With Independent Parts
Aggregation is an association with a whole-part meaning: one object is a container or group, the others are its members. The parts:
are usually created outside the whole and passed in,
can outlive the whole,
can be shared by several wholes at the same time.
Examples: a department and its professors, a playlist and its songs, a team and its players. In UML it is drawn with a hollow diamond on the whole's side.
┌────────────┐ 1..* * ┌───────────┐
│ Department │◇─────────────────│ Professor │
└────────────┘ └───────────┘
(a professor may belong to several departments) import java.util.ArrayList;
import java.util.List;
class Professor {
private final String name;
Professor(String name) { this.name = name; }
String getName() { return name; }
}
class Department {
private final String name;
private final List<Professor> members = new ArrayList<>();
Department(String name) { this.name = name; }
void addMember(Professor p) { members.add(p); } // part is created OUTSIDE and passed in
void print() {
System.out.print(name + ":");
for (Professor p : members) System.out.print(" " + p.getName());
System.out.println();
}
}
public class AggregationDemo {
public static void main(String[] args) {
Professor gupta = new Professor("Dr. Gupta");
Professor iyer = new Professor("Dr. Iyer");
Department cse = new Department("CSE");
Department ai = new Department("AI Centre");
cse.addMember(gupta);
cse.addMember(iyer);
ai.addMember(gupta); // the same professor belongs to two wholes
cse.print();
ai.print();
cse = null; // the CSE department is closed...
System.out.println(gupta.getName() + " still works at the AI Centre"); // ...parts live on
ai.print();
}
}Output:
CSE: Dr. Gupta Dr. Iyer
AI Centre: Dr. Gupta
Dr. Gupta still works at the AI Centre
AI Centre: Dr. GuptaDr. Gupta was shared by two departments, and closing CSE did not destroy him. The Department merely collects references to professors it never created.
A word of honesty: the official UML specification deliberately leaves the meaning of the hollow diamond ("shared aggregation") loosely defined. Many experienced designers simply draw a plain association instead. For exams and interviews, though, the distinction above (whole-part, independent lifetime, sharable) is the expected answer.
Composition: The Whole Owns Its Parts
Composition is the strongest form. The part is owned by the whole:
a part belongs to only one whole at a time,
the whole is responsible for the part's lifetime: usually it creates the part, and when the whole is destroyed, its parts are destroyed with it,
the part has little meaning on its own: a room without a house, an order line without an order, a chapter without its book.
In UML it is drawn with a filled diamond on the whole's side.
┌───────┐ 1 1..* ┌──────┐
│ House │◆──────────────────│ Room │
└───────┘ └──────┘
(each room belongs to exactly one house) import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class House {
// Room is a part that only makes sense inside its House
static final class Room {
private final String type;
private final double areaSqFt;
private Room(String type, double areaSqFt) { this.type = type; this.areaSqFt = areaSqFt; }
String type() { return type; }
double areaSqFt() { return areaSqFt; }
}
private final String address;
private final List<Room> rooms = new ArrayList<>();
House(String address) {
this.address = address;
rooms.add(new Room("Hall", 300)); // the whole CREATES its parts
rooms.add(new Room("Kitchen", 120));
}
void addRoom(String type, double area) { // parts are added only through the whole
rooms.add(new Room(type, area));
}
List<Room> rooms() { // read-only view: outsiders cannot add or remove
return Collections.unmodifiableList(rooms);
}
double totalArea() {
double sum = 0;
for (Room r : rooms) sum += r.areaSqFt();
return sum;
}
String address() { return address; }
}
public class CompositionDemo {
public static void main(String[] args) {
House h = new House("12, MG Road");
h.addRoom("Bedroom", 180);
for (House.Room r : h.rooms()) System.out.println(r.type() + " " + r.areaSqFt());
System.out.println(h.address() + " total = " + h.totalArea() + " sq ft");
try {
h.rooms().clear(); // try to remove rooms from outside
} catch (UnsupportedOperationException e) {
System.out.println("Cannot modify rooms from outside the House");
}
// When h becomes unreachable, its rooms become unreachable too.
}
}Output:
Hall 300.0
Kitchen 120.0
Bedroom 180.0
12, MG Road total = 600.0 sq ft
Cannot modify rooms from outside the HouseHow the code enforces composition:
Room's constructor isprivate(inside the nested class), so onlyHousecan create rooms. Nobody can make a "free-floating" room or put one room into two houses.The house creates its rooms itself, in the constructor and in
addRoom().rooms()returns a read-only view, so outside code cannot add or remove parts behind the house's back.No other object holds a reference to the rooms list, so when the house becomes unreachable, its rooms become unreachable too (unless some outside code deliberately kept a reference to an individual
Roomit read throughrooms()), and the garbage collector reclaims them together.
Composition in C++: lifetimes you can see
Java has a garbage collector, so "the part dies with the whole" is about reachability. C++ makes lifetimes explicit, which shows the difference very clearly. A member object (stored by value) is pure composition: it is constructed before the owner's constructor body runs and destroyed right after the owner's destructor body. A non-owning pointer or reference is just an association: the owner never destroys what it points to.
#include <iostream>
#include <string>
#include <utility>
class Engine {
public:
Engine() { std::cout << " Engine built\n"; }
~Engine() { std::cout << " Engine destroyed\n"; }
void start() const { std::cout << " Engine started\n"; }
};
class Driver {
std::string name;
public:
explicit Driver(std::string n) : name(std::move(n)) { std::cout << " Driver " << name << " born\n"; }
~Driver() { std::cout << " Driver " << name << " gone\n"; }
const std::string& getName() const { return name; }
};
class Car {
Engine engine; // COMPOSITION: a member object, lives and dies with the Car
const Driver* driver = nullptr; // ASSOCIATION: a non-owning pointer, Car never deletes it
public:
Car() { std::cout << " Car built\n"; }
~Car() { std::cout << " Car destroyed\n"; }
void assign(const Driver& d) { driver = &d; }
void drive() const {
engine.start();
if (driver) std::cout << " " << driver->getName() << " is driving\n";
}
};
int main() {
std::cout << "create driver:\n";
Driver meera("Meera");
{
std::cout << "create car:\n";
Car car;
car.assign(meera);
car.drive();
std::cout << "car goes out of scope:\n";
}
std::cout << "driver still exists: " << meera.getName() << '\n';
std::cout << "end of main:\n";
}Output:
create driver:
Driver Meera born
create car:
Engine built
Car built
Engine started
Meera is driving
car goes out of scope:
Car destroyed
Engine destroyed
driver still exists: Meera
end of main:
Driver Meera goneThe engine was built and destroyed together with the car (composition). The driver existed before the car and survived it (association). In C++, ownership of a part created on the heap is expressed with std::unique_ptr (one owner, composition-like) or std::shared_ptr (shared ownership, aggregation-like), while a raw pointer or reference usually means "I use it, I do not own it".
Comparing the Three
Point | Association | Aggregation | Composition |
|---|---|---|---|
Relationship | "uses / knows" | "has-a" (whole-part) | "owns / is made of" (whole-part) |
Ownership | None | Weak | Strong, exclusive |
Part outlives the whole? | Yes (no whole at all) | Yes | No |
Part shared by several wholes? | Yes | Yes | No |
Who creates the part? | Anyone | Usually outside code, then passed in | Usually the whole itself |
UML symbol | Plain line (arrow for direction) | Hollow diamond ◇ at the whole | Filled diamond ◆ at the whole |
Examples | Teacher–Student, Doctor–Patient | Department–Professor, Playlist–Song | House–Room, Order–OrderLine, Book–Chapter |
Typical Java code | Field referencing an object given from outside | Collection of objects given from outside | Fields created inside, never handed out for modification |
A quick test for any pair of classes
Is B a kind of A? → inheritance ("is-a")
Is B a part of A?
no → association
yes: can B exist without A,
or belong to several A's? → aggregation
no, A owns B's lifetime → compositionRemember that the answer depends on the system you are modelling, not on the real world alone. In a car showroom application an Engine is composed into a Car. In a garage application where engines are removed, repaired and fitted into other cars, the same relationship is better modelled as aggregation.
Composition Over Inheritance
A famous design guideline (from the "Gang of Four" design patterns book) says: favour object composition over class inheritance. The reason is that inheritance exposes everything the parent can do and ties the child tightly to the parent's implementation. Composition lets a class reuse another class's work while exposing only what it chooses.
The Java library itself contains a well-known example. java.util.Stack was written (in Java 1.0) as a subclass of Vector. So a stack "is-a" vector, and inherits methods like add(index, x) and remove(Object) that break the last-in-first-out rule:
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;
// Composition: our stack HAS-A deque and exposes only stack operations
class SafeStack<T> {
private final Deque<T> items = new ArrayDeque<>();
void push(T x) { items.push(x); }
T pop() { return items.pop(); }
T peek() { return items.peek(); }
boolean isEmpty() { return items.isEmpty(); }
int size() { return items.size(); }
}
public class StackDemo {
public static void main(String[] args) {
Stack<Integer> legacy = new Stack<>(); // java.util.Stack IS-A Vector (inheritance)
legacy.push(1);
legacy.push(2);
legacy.add(0, 99); // inherited from Vector: insert at the BOTTOM
legacy.remove(Integer.valueOf(2)); // remove from the middle: not a stack operation
System.out.println("legacy Stack = " + legacy); // bottom ... top
System.out.println("legacy pop -> " + legacy.pop());
SafeStack<Integer> safe = new SafeStack<>();
safe.push(1);
safe.push(2);
// safe.add(0, 99); // does not compile: no such method
System.out.println("SafeStack pop -> " + safe.pop() + ", size = " + safe.size());
}
}Output:
legacy Stack = [99, 1]
legacy pop -> 1
SafeStack pop -> 2, size = 1The legacy stack let us insert 99 at the bottom and pull 2 out of the middle. SafeStack has-a deque inside and exposes only push, pop, peek, isEmpty and size, so misuse does not even compile. It could also switch to a different internal structure later without affecting any caller. (The Java documentation itself recommends using Deque implementations such as ArrayDeque instead of Stack.)
Use inheritance when there is a genuine "is-a" relationship and the child should support everything the parent supports. Otherwise, compose.
Common Mistakes
Putting the diamond on the wrong end. The diamond always sits next to the whole (the container), not the part.
Calling every "has-a" composition. If the part is created elsewhere, shared, or survives the whole, it is aggregation (or plain association).
Leaking parts of a composition. Returning the internal mutable list (
return rooms;) lets outsiders add, remove or share parts, silently turning composition into something weaker.Half-updated bidirectional links. Setting
teacher.studentsbut forgettingstudent.teachersleaves the model inconsistent. Update both sides in one method.Using inheritance just to reuse code ("
Car extends Engineso the car can callstart()"). A car is not an engine; it has one.Thinking Java "destroys" composed parts. Java has no destructors; the parts are simply garbage collected once nothing refers to them. C++ really destroys member objects with their owner.
Interview and GATE-Style Questions
Q1. What is the difference between aggregation and composition?
Both are whole-part relationships. In aggregation the part can exist independently and may be shared by several wholes (department–professor). In composition the part belongs to exactly one whole and its lifetime is controlled by the whole (house–room). Composition is the stronger form.
Q2. Classify: (a) Library–Book (b) Human–Heart (c) Customer–Bank (d) Playlist–Song (e) Invoice–InvoiceLine
(a) Aggregation in most systems (books exist before and after joining the library). (b) Composition. (c) Association (neither is part of the other). (d) Aggregation (one song can be in many playlists). (e) Composition (a line is meaningless without its invoice).
Q3. In a UML class diagram, what do a hollow diamond and a filled diamond mean, and at which end are they drawn?
Hollow diamond: aggregation. Filled diamond: composition. Both are drawn at the end of the whole (the container class).
Q4. Why is "favour composition over inheritance" good advice?
Inheritance exposes the whole parent interface and couples the child to the parent's implementation (changes in the parent can break children). Composition reuses behaviour through a private member, exposes only the chosen operations, and allows the internal object to be replaced, even at run time. java.util.Stack extends Vector is the classic example of inheritance exposing unwanted operations.
Q5. In C++, which of these express composition: a member Engine e;, a member Engine* e;, a member std::unique_ptr<Engine> e;?
Engine e;, a member Engine* e;, a member std::unique_ptr<Engine> e;?Engine e; and std::unique_ptr<Engine> e; both mean the object owns its engine, which is destroyed with it. A raw Engine* by itself says nothing about ownership and usually signals a non-owning association.
Q6. Is every composition an association?
Yes. Association is the general relationship; aggregation is a specialised association with whole-part meaning; composition is a specialised aggregation with exclusive ownership.
Summary
Association: objects are linked and collaborate; independent lifetimes; described by direction and multiplicity.
Aggregation (◇): whole-part, but parts are created outside, can be shared and can outlive the whole.
Composition (◆): whole-part with exclusive ownership; the whole controls the parts' lifetime.
Composition ⊂ aggregation ⊂ association.
In Java, enforce composition by creating parts inside the whole and never leaking them; in C++, by holding members by value or
unique_ptr.Prefer composition over inheritance unless there is a true, complete "is-a" relationship.
Ask two questions: "Is it a part?" and "Can it live without the whole?" The answers give you association, aggregation or composition.