Skip to lesson

Aggregation: a whole that shares its parts

Aggregation is a HAS-A link where the parts have a life of their own. A department has teachers, but the college hired them, not the department. If the department closes, the teachers still exist and can join another one.

A whole that groups independent parts

Aggregation is a weak HAS-A relationship in which a whole groups parts that can exist without it. The parts are created outside and passed in, so they can be shared and can outlive the whole.

Aggregation is a kind of association (opens in a new tab) with a clear whole and parts. To spot it, ask: "If the whole is gone, do the parts still make sense?" A teacher without a department is still a teacher.

Java
Teacher ravi = new Teacher("Ravi", "Maths");   // the part is made outsideDepartment cse = new Department("CSE");cse.addTeacher(ravi);                          // the whole only keeps a reference

When the answer is yes, it is aggregation: a department has teachers, a playlist has songs, a cricket team has players, a WhatsApp group has members. People call it "has-a, but does not own".

Parts come from outside

In code, aggregation shows in where the parts are created: outside the whole, then passed in through the constructor or an add method. The whole only stores references and never writes new Teacher(...) itself.

Memory picture. Department CSE holds two references, to the Teacher objects Ravi and Meena. Department ECE holds one reference, to the same Ravi object. The teachers are separate objects: the departments only point at them.

Example 1 · A department with teachers from outside

DepartmentDemo.javaJava
class Teacher {    private String name;    private String subject;
    Teacher(String name, String subject) {        this.name = name;        this.subject = subject;    }
    String describe() { return name + " (" + subject + ")"; }}
class Department {    private String name;    private Teacher[] teachers = new Teacher[5];    private int count;
    Department(String name) { this.name = name; }
    void addTeacher(Teacher t) {        if (count < teachers.length) {            teachers[count] = t;            count++;        }    }
    void show() {        System.out.println(name + " department:");        for (int i = 0; i < count; i++) {            System.out.println("  " + teachers[i].describe());        }    }}
public class DepartmentDemo {    public static void main(String[] args) {        Teacher ravi = new Teacher("Ravi", "Java");        Teacher meena = new Teacher("Meena", "DBMS");        Department cse = new Department("CSE");        cse.addTeacher(ravi);        cse.addTeacher(meena);        cse.show();    }}
Output
CSE department:
  Ravi (Java)
  Meena (DBMS)

What this code does

  • The teachers are created in main and passed into addTeacher. Department never calls new Teacher.
  • The department only groups references to teachers who already exist. That is aggregation.

Example 2 · One song in two playlists

PlaylistDemo.javaJava
class Song {    private String title;    private int plays;
    Song(String title) { this.title = title; }
    void play() { plays++; }    String describe() { return title + " (" + plays + " plays)"; }}
class Playlist {    private String name;    private Song[] songs = new Song[10];    private int count;
    Playlist(String name) { this.name = name; }
    void add(Song s) {        songs[count] = s;        count++;    }
    void playAll() {        for (int i = 0; i < count; i++) {            songs[i].play();        }    }
    void show() {        System.out.println(name + ": " + songs[0].describe());    }}
public class PlaylistDemo {    public static void main(String[] args) {        Song kesariya = new Song("Kesariya");        Playlist gym = new Playlist("Gym");        Playlist study = new Playlist("Study");        gym.add(kesariya);        study.add(kesariya);        gym.playAll();        study.playAll();        gym.show();        study.show();    }}
Output
Gym: Kesariya (2 plays)
Study: Kesariya (2 plays)

What this code does

  • Both playlists hold a reference to the same Song object. Playing it from either playlist adds to one shared count.
  • Sharing a part between wholes is normal in aggregation, because the part does not belong to just one of them.

Because the part is passed in, the same part can be passed to two wholes, like Ravi in the picture. Both wholes point at one object, so a change to it shows in both, as with the shared part (opens in a new tab) of the last lesson.

Parts outlive the whole

Java frees an object only when nothing points to it any more, as in Many objects, references and null (opens in a new tab). If main still points to a teacher, closing the department cannot remove him.

Example 3 · The teacher outlives the department

OutliveDemo.javaJava
class Teacher {    private String name;
    Teacher(String name) { this.name = name; }
    String getName() { return name; }}
class Department {    private String name;    private Teacher[] teachers = new Teacher[5];    private int count;
    Department(String name) { this.name = name; }
    void addTeacher(Teacher t) {        teachers[count] = t;        count++;        System.out.println(t.getName() + " joined " + name);    }}
public class OutliveDemo {    public static void main(String[] args) {        Teacher ravi = new Teacher("Ravi");        Department cse = new Department("CSE");        cse.addTeacher(ravi);
        cse = null;        System.out.println("CSE closed");
        Department ece = new Department("ECE");        ece.addTeacher(ravi);        System.out.println(ravi.getName() + " is still here");    }}
Output
Ravi joined CSE
CSE closed
Ravi joined ECE
Ravi is still here

What this code does

  • After cse = null, nothing points to the CSE department, so Java can clean it up.
  • The variable ravi still points to the teacher, so he lives on and joins ECE. The part outlived its first whole.

Java has no keyword for aggregation or composition: both are a field holding a reference. The difference is a design choice, and Composition (opens in a new tab) shows the other choice, where the whole makes its parts and nobody else points to them.

"Parts outlive the whole" does not mean Java protects them. A part stays alive only because something else, like ravi in main, still points to it.

Removing a part, and the traps

Removing a part means "this part leaves the group", not "destroy it". Shift the later items one place left, set the last filled place to null, and reduce count.

Example 4 · Removing a part without destroying it

RemoveDemo.javaJava
class Player {    private String name;
    Player(String name) { this.name = name; }
    String getName() { return name; }}
class Team {    private Player[] players = new Player[5];    private int count;
    void add(Player p) {        players[count] = p;        count++;    }
    void remove(String name) {        for (int i = 0; i < count; i++) {            if (players[i].getName().equals(name)) {                for (int j = i; j < count - 1; j++) {                    players[j] = players[j + 1];                }                players[count - 1] = null;                count--;                return;            }        }    }
    void show() {        String line = "Team:";        for (int i = 0; i < count; i++) {            line = line + " " + players[i].getName();        }        System.out.println(line);    }}
public class RemoveDemo {    public static void main(String[] args) {        Player rohit = new Player("Rohit");        Team team = new Team();        team.add(new Player("Virat"));        team.add(rohit);        team.add(new Player("Jadeja"));        team.show();        team.remove("Rohit");        team.show();        System.out.println("On the bench: " + rohit.getName());    }}
Output
Team: Virat Rohit Jadeja
Team: Virat Jadeja
On the bench: Rohit

What this code does

  • To remove, shift the later players one place left, clear the last filled place with null, and do count--.
  • The team forgets Rohit, but the Player object is fine: rohit still points to it and can use it.

Example 5 · Trap: the whole makes its own copies

CopyTrapDemo.javaJava
class Song {    private String title;    private int plays;
    Song(String title) { this.title = title; }
    void play() { plays++; }    String describe() { return title + " (" + plays + " plays)"; }}
class Playlist {    private String name;    private Song[] songs = new Song[10];    private int count;
    Playlist(String name) { this.name = name; }
    void add(String title) {        songs[count] = new Song(title);        count++;    }
    void playFirst() { songs[0].play(); }
    void show() {        System.out.println(name + ": " + songs[0].describe());    }}
public class CopyTrapDemo {    public static void main(String[] args) {        Playlist gym = new Playlist("Gym");        Playlist study = new Playlist("Study");        gym.add("Kesariya");        study.add("Kesariya");        gym.playFirst();        study.playFirst();        gym.show();        study.show();    }}
Output
Gym: Kesariya (1 plays)
Study: Kesariya (1 plays)

What this code does

  • add(String title) creates a new Song inside the playlist, so each playlist gets its own copy. The song was played twice, but each copy shows 1.
  • Songs should be shared, so pass in a Song object made outside: add(Song s), as in Example 2.

Two traps. Forgetting count-- after the shift leaves the last item showing twice. And creating the parts inside the whole by mistake, like add(String title) doing new Song(title), gives every whole its own copy, so nothing is shared any more.

Next step

Check your understanding

11 quick questions