Skip to lesson

Composition: a whole that owns its parts

Composition is the strongest HAS-A link: the whole owns its parts. A house creates its rooms, and the rooms make no sense without that house. When the house is gone, its rooms go with it.

A whole that owns its parts

Composition is a strong HAS-A relationship in which the whole creates and owns its parts. The parts belong to that whole only and live only as long as it does, like the rooms of a house.

Ask the aggregation question again: "If the whole is gone, do the parts still make sense?" For a house and its rooms the answer is no. That is composition.

Example 1 · A house creates its rooms

HouseDemo.javaJava
class Room {    private String name;
    Room(String name) { this.name = name; }
    String getName() { return name; }}
class House {    private String owner;    private Room[] rooms;
    House(String owner, String[] roomNames) {        this.owner = owner;        rooms = new Room[roomNames.length];        for (int i = 0; i < roomNames.length; i++) {            rooms[i] = new Room(roomNames[i]);        }    }
    void show() {        System.out.println(owner + "'s house has " + rooms.length + " rooms:");        for (int i = 0; i < rooms.length; i++) {            System.out.println("- " + rooms[i].getName());        }    }}
public class HouseDemo {    public static void main(String[] args) {        String[] names = { "Hall", "Kitchen", "Bedroom" };        House h = new House("Kavya", names);        h.show();    }}
Output
Kavya's house has 3 rooms:
- Hall
- Kitchen
- Bedroom

What this code does

  • main passes only room names. The House constructor itself calls new Room(...), so the house owns every room.
  • The rooms are in a private array and no method hands them out. Only the house can reach them, so they live and die with it.

Other examples: an order owns its order lines, an employee owns an ID card, a human owns a heart. Like aggregation, composition is just a field holding a reference; the difference is who creates the part and whether anyone else may hold it.

Order of execution

A house and its rooms, from start to end

Tap the steps in the order they happen.

class Room {
private String name;
Room(String name) { this.name = name; }
}
class House {
private Room[] rooms;
House(String[] names) {
rooms = new Room[names.length];
for (int i = 0; i < names.length; i++) {
rooms[i] = new Room(names[i]);
}
}
}
// in main
House h = new House(new String[] { "Hall", "Kitchen" });
h = null;

Parts are created inside the whole

The clearest sign of composition is that the whole calls new for its parts. The caller passes only data (names, prices, sizes), never ready-made part objects. Parts can also be made later by a method of the whole.

Example 2 · An order builds its own lines

OrderDemo.javaJava
class OrderLine {    private String item;    private int price;    private int qty;
    OrderLine(String item, int price, int qty) {        this.item = item;        this.price = price;        this.qty = qty;    }
    int amount() { return price * qty; }    String describe() { return qty + " x " + item + " = Rs. " + amount(); }}
class Order {    private OrderLine[] lines = new OrderLine[10];    private int count;
    void addLine(String item, int price, int qty) {        lines[count] = new OrderLine(item, price, qty);        count++;    }
    void printBill() {        int total = 0;        for (int i = 0; i < count; i++) {            System.out.println(lines[i].describe());            total = total + lines[i].amount();        }        System.out.println("Total: Rs. " + total);    }}
public class OrderDemo {    public static void main(String[] args) {        Order o = new Order();        o.addLine("Masala Dosa", 80, 2);        o.addLine("Filter Coffee", 30, 3);        o.printBill();    }}
Output
2 x Masala Dosa = Rs. 160
3 x Filter Coffee = Rs. 90
Total: Rs. 250

What this code does

  • Parts can also be created later: addLine builds a new OrderLine inside the order each time.
  • An order line has no meaning outside its order, and no other object ever holds it. That is composition.

Because only the whole holds its parts, the parts become unreachable at the same moment as the whole, and the garbage collector can free them together. That is what "the parts die with the whole" means in Java.

Do not let the parts leak

Ownership breaks when outside code gets a reference to a part. A getter such as IdCard getCard() { return card; } hands out the real card, and the caller can change it behind the employee's back.

Example 3 · A leaking getter breaks ownership

LeakDemo.javaJava
class IdCard {    private String number;    private int validTill;
    IdCard(String number, int validTill) {        this.number = number;        this.validTill = validTill;    }
    void setValidTill(int year) { validTill = year; }    String describe() { return number + " valid till " + validTill; }}
class Employee {    private String name;    private IdCard card;
    Employee(String name, String cardNumber, int validTill) {        this.name = name;        this.card = new IdCard(cardNumber, validTill);    }
    IdCard getCard() { return card; }
    void show() { System.out.println(name + ": " + card.describe()); }}
public class LeakDemo {    public static void main(String[] args) {        Employee e = new Employee("Arjun", "EMP-204", 2026);        e.show();        IdCard c = e.getCard();        c.setValidTill(2099);        e.show();    }}
Output
Arjun: EMP-204 valid till 2026
Arjun: EMP-204 valid till 2099

What this code does

  • The employee creates its card, which is good. But getCard() returns the real card object, not a copy.
  • Outside code now holds a reference to the part and changes it. The employee's card says 2099 although nobody asked the employee.

Example 4 · The fix: copy out (or return only data)

CopyOutDemo.javaJava
class IdCard {    private String number;    private int validTill;
    IdCard(String number, int validTill) {        this.number = number;        this.validTill = validTill;    }
    String getNumber() { return number; }    int getValidTill() { return validTill; }    void setValidTill(int year) { validTill = year; }    String describe() { return number + " valid till " + validTill; }}
class Employee {    private String name;    private IdCard card;
    Employee(String name, String cardNumber, int validTill) {        this.name = name;        this.card = new IdCard(cardNumber, validTill);    }
    IdCard getCard() {        return new IdCard(card.getNumber(), card.getValidTill());    }
    String getCardNumber() { return card.getNumber(); }
    void show() { System.out.println(name + ": " + card.describe()); }}
public class CopyOutDemo {    public static void main(String[] args) {        Employee e = new Employee("Arjun", "EMP-204", 2026);        IdCard c = e.getCard();        c.setValidTill(2099);        e.show();        System.out.println("Copy: " + c.describe());        System.out.println("Number only: " + e.getCardNumber());    }}
Output
Arjun: EMP-204 valid till 2026
Copy: EMP-204 valid till 2099
Number only: EMP-204

What this code does

  • getCard() now returns a copy: a new IdCard with the same data. Changing the copy cannot touch the real card.
  • getCardNumber() is often even better: it gives the caller just the data it needs and never exposes the part.

The fix is the defensive copy from Read-only objects (opens in a new tab), now for an object part: copy in when the constructor receives a part, and copy out when a getter must return one. Often it is simpler to return only the data the caller needs, like getCardNumber().

Aggregation vs composition side by side

Both are HAS-A and both are written with a field. The difference is who creates the part and who else can use it. One class often has both: a car owns its engine but only uses a driver.

Two class diagrams. Aggregation: Department joined to Teacher by a line with a hollow diamond at the Department end; teachers are made outside and outlive it. Composition: House joined to Room by a line with a filled diamond; rooms are made inside and end with it.

Example 5 · One class, both kinds: car, engine and driver

BothKindsDemo.javaJava
class Engine {    private int cc;
    Engine(int cc) { this.cc = cc; }
    String describe() { return cc + " cc engine"; }}
class Driver {    private String name;
    Driver(String name) { this.name = name; }
    String getName() { return name; }}
class Car {    private String model;    private Engine engine;    private Driver driver;
    Car(String model, int cc, Driver driver) {        this.model = model;        this.engine = new Engine(cc);        this.driver = driver;    }
    void drive() {        System.out.println(driver.getName() + " drives the " + model + " (" + engine.describe() + ")");    }}
public class BothKindsDemo {    public static void main(String[] args) {        Driver ramesh = new Driver("Ramesh");        Car swift = new Car("Swift", 1197, ramesh);        swift.drive();        swift = null;        Car nexon = new Car("Nexon", 1199, ramesh);        nexon.drive();    }}
Output
Ramesh drives the Swift (1197 cc engine)
Ramesh drives the Nexon (1199 cc engine)

What this code does

  • The engine is created inside Car from a number (composition). The driver is created outside and passed in (aggregation).
  • When the Swift is scrapped (swift = null), nothing points to its engine any more, so both can be cleaned up. But Ramesh lives on and drives the Nexon.
  • Who creates the part: aggregation → outside code; composition → the whole itself.
  • Sharing: aggregation → parts can be shared; composition → one whole only.
  • Life: aggregation → parts outlive the whole; composition → parts end with it.
  • Diagram: a hollow diamond for aggregation, a filled diamond for composition, at the whole's end.

Next step

Check your understanding

11 quick questions