IB COMPUTER SCIENCE | B3.2.4 Composition and Aggregation (HL)

Lesson objective

Explain how composition and aggregation assemble objects from smaller components, and justify ownership, sharing and lifetime rules in class relationships.

Learn

B3.2.4 | COMPOSITION AND AGGREGATION (HL ONLY)

01 | BUILD A LARGER OBJECT FROM SMALLER OBJECTS

A robotics team produces a design report. The report contains sections such as Testing and Evaluation. The same team also runs a club whose members are students. Both situations involve a whole and its parts, but the relationships do not mean the same thing.

A section in this report belongs to that report. In our application, deleting the report removes its sections as active report content. A student, however, exists before joining the club and can continue learning after the club closes. The club does not own the student’s existence.

Composition and aggregation let us describe these different whole–part relationships. They help us decide how objects are assembled, reused, shared and managed through their lifetimes.

02 | START WITH OBJECT REFERENCES

An object can store a reference to another object in one of its attributes. A reference gives the program a way to reach an existing object. Storing a reference is not the same as copying the object, and it does not by itself decide who owns it.

sam = Student("Sam")
members = [sam]
sam.award_point()
print(members[0].points)
# 1

Run this fragment after defining Student later in the lesson. sam and members[0] refer to the same Student object, so the updated points are visible through either route. This shared-reference idea is essential for understanding aggregation.

The relationship comes from the model’s rules, not just the fact that one variable appears inside another object. We must ask what the stored object represents and whether its lifetime belongs to the containing object.

03 | ASSOCIATION, AGGREGATION AND COMPOSITION

Relationship Meaning Example in this lesson
Association Objects are related or collaborate; no whole–part ownership is necessarily implied A teacher reviews a report
Aggregation A whole groups independently existing parts A club groups students
Composition A whole owns parts whose modelled lifetime depends on it A report owns its sections

Association is the broad relationship. Aggregation and composition express more specific whole–part meanings. The important distinction for this syllabus is independence: aggregated components can function independently, while composed components belong to the containing whole in the model.

These are design meanings. Python and Java references do not carry a built-in switch labelled aggregation or composition. The classes and the wider application must preserve the intended rules.

04 | COMPOSITION: THE WHOLE OWNS ITS PARTS

Composition is a strong whole–part relationship. A part belongs to at most one composite owner at a time, and its lifetime in the model is tied to that owner. In our report system, each ReportSection belongs to one Report and is not offered as a standalone resource.

The report creates its sections, uses them to provide report operations and removes them when the report is deleted. Another report can have similar text, but that would be a different section object with its own identity.

For this example we do not transfer sections between reports. Some larger models permit an explicit transfer that preserves single ownership; such a rule must be designed rather than assumed.

05 | AGGREGATION: THE PARTS EXIST INDEPENDENTLY

Aggregation is a weaker whole–part relationship. A Club stores references to Student objects that already exist. The students are not created merely as internal club components and do not cease to exist when the club disbands.

Sam can be a member of both Robotics and Coding. Both clubs can refer to the same Student object while holding their own membership lists. Closing Robotics removes that membership group; it does not delete Sam or the Coding membership.

Independent lifetime is the key idea. Sharing across multiple wholes is possible and useful in this example, but a particular application may impose a rule allowing only one current membership. That rule would not automatically make the student composition-owned.

06 | READ THE UML DIAMONDS

The 1 near Report means each section belongs to one report. The 0..* near ReportSection means a report may contain zero or more sections. For the club example, a club can have many students and a student can join many clubs.

A diamond describes a whole–part relationship. The hollow triangle used for inheritance has a different meaning and points towards the superclass. Do not interchange those symbols.

07 | INHERITANCE ASKS A DIFFERENT QUESTION

Question Suitable relationship Reason
Is a Robot a kind of Device? Inheritance Robot specialises the Device concept
Does a Report contain its own sections? Composition Sections form owner-dependent parts
Does a Club group independent Students? Aggregation Students retain their own lifetime

A report is not a kind of section, and a club is not a kind of student. Trying to inherit those classes would confuse the model. These are has-a or groups-a relationships rather than is-a specialisations.

Using component objects gives each smaller class a focused responsibility. The whole can coordinate those components instead of inheriting unrelated behaviour.

08 | PYTHON: DEFINE THE OWNED PART

class _ReportSection:
    def __init__(self, title, text):
        self.title = title
        self.text = text

A section stores a heading and its content. The leading underscore in _ReportSection signals that it is an internal implementation class for this module. Python does not make it inaccessible; the underscore is a convention that cooperating code should respect.

The composition rule will come from how Report creates and manages these sections. The class name alone does not guarantee ownership. Our public Report operations will accept ordinary strings and return title values rather than expose the section objects.

09 | PYTHON: THE REPORT CREATES ITS SECTIONS

class Report:
    def __init__(self, title):
        self.title = title
        self._sections = []
        self._active = True

    def _ensure_active(self):
        if not self._active:
            raise ValueError("Report has been deleted")

    def add_section(self, title, text):
        self._ensure_active()
        self._sections.append(_ReportSection(title, text))

Each report gets its own new list. add_section creates a new section object inside that report’s operation. The caller supplies the values, not an existing shared section object. This supports exclusive ownership in our design.

_active records whether this report remains usable in the application. _ensure_active raises an exception if an operation is attempted after deletion. This is an explicit domain rule, not a request for immediate memory destruction. The complete class follows next.

10 | PROVIDE A SAFE VIEW AND A DELETION OPERATION

class _ReportSection:
    def __init__(self, title, text):
        self.title = title
        self.text = text

class Report:
    def __init__(self, title):
        self.title = title
        self._sections = []
        self._active = True

    def _ensure_active(self):
        if not self._active:
            raise ValueError("Report has been deleted")

    def add_section(self, title, text):
        self._ensure_active()
        self._sections.append(_ReportSection(title, text))

    def section_titles(self):
        self._ensure_active()
        return tuple(section.title for section in self._sections)

    def delete(self):
        self._sections.clear()
        self._active = False

section_titles returns a tuple of title strings. It does not hand out the mutable internal list or the owned section objects. A caller can display the titles while the report retains control of the parts.

delete clears the report’s section references and marks the report inactive. Future attempts to add or list sections raise ValueError. In the application model, the report and its sections have stopped being active resources. Calling delete again is harmless here.

For focus, the example assumes title and text arguments are strings. A production editor would add appropriate validation, storage and recovery rules.

11 | AGGREGATION STARTS WITH INDEPENDENT STUDENTS

class Student:
    def __init__(self, name):
        self.name = name
        self.points = 0

    def award_point(self):
        self.points += 1

sam = Student("Sam")
sam.award_point()
print(sam.name, sam.points)
# Sam 1

Student can be used without any Club object. The initializer creates student state and award_point changes that state. A club relationship is optional rather than a condition for the student’s existence.

We use public attributes here to keep attention on object relationships. A larger system could encapsulate the points and name behind controlled operations without changing the fact that students have an independent lifetime.

12 | PYTHON: A CLUB RECEIVES EXISTING OBJECTS

class Student:
    def __init__(self, name):
        self.name = name
        self.points = 0

    def award_point(self):
        self.points += 1

class Club:
    def __init__(self, name, members):
        self.name = name
        self._members = list(members)
        self._active = True

    def member_summaries(self):
        if not self._active:
            raise ValueError("Club has been disbanded")
        return tuple(f"{student.name}: {student.points}" for student in self._members)

    def disband(self):
        self._members.clear()
        self._active = False

The caller creates students first, then passes references to Club. list(members) creates a new membership list containing references to the same students. It does not create a new Student for every entry.

member_summaries asks each existing student for its current name and points through those references. disband clears only this club’s list and makes its membership operations inactive. It does not modify or destroy student state.

Keeping membership in a separate list prevents one club from accidentally clearing the caller’s list. The object references inside the list remain shared, which is exactly what we want.

13 | SHARING ONE STUDENT BETWEEN TWO CLUBS

sam = Student("Sam")
robotics = Club("Robotics", [sam])
coding = Club("Coding", [sam])

sam.award_point()
print(robotics.member_summaries())
print(coding.member_summaries())
# ('Sam: 1',)
# ('Sam: 1',)

There are two Club objects and one Student object. Both lists contain a reference to Sam. Awarding one point updates that one student, so both clubs see the new value when they produce summaries.

A one-item tuple is displayed with a trailing comma in Python. The comma is not another member. The outputs are immutable snapshots of string values, while the live shared Student object holds the current points.

14 | COPY THE CONTAINER, UNDERSTAND THE CONTENTS

sam = Student("Sam")
original_members = [sam]
robotics = Club("Robotics", original_members)
original_members.clear()
print(robotics.member_summaries())
# ('Sam: 0',)
sam.award_point()
print(robotics.member_summaries())
# ('Sam: 1',)

Clearing original_members does not clear the club’s copied list. However, changing Sam still affects the summaries because both lists originally held references to that same student. This is a shallow container copy.

Aggregation does not mean duplicating every part. A deep copy that manufactured a different student would change the identity model and could produce inconsistent records for the same person. Choose copying based on the requirements, not on a vague goal of making everything independent.

15 | STEP THROUGH OWNERSHIP AND LIFETIME

Follow one report with its owned sections and two clubs sharing Sam. Predict what remains usable when a club is disbanded and when the report is deleted. The display shows application state, not a memory collector’s internal actions.

16 | A COMPLETE PYTHON PROGRAM

Save this as relationships_demo.py and click Run in your editor. All class definitions come first. The main statements then assemble the objects and exercise the two different lifetime rules.

class _ReportSection:
    def __init__(self, title, text):
        self.title = title
        self.text = text

class Report:
    def __init__(self, title):
        self.title = title
        self._sections = []
        self._active = True

    def _ensure_active(self):
        if not self._active:
            raise ValueError("Report has been deleted")

    def add_section(self, title, text):
        self._ensure_active()
        self._sections.append(_ReportSection(title, text))

    def section_titles(self):
        self._ensure_active()
        return tuple(section.title for section in self._sections)

    def delete(self):
        self._sections.clear()
        self._active = False

class Student:
    def __init__(self, name):
        self.name = name
        self.points = 0

    def award_point(self):
        self.points += 1

class Club:
    def __init__(self, name, members):
        self.name = name
        self._members = list(members)
        self._active = True

    def member_summaries(self):
        if not self._active:
            raise ValueError("Club has been disbanded")
        return tuple(f"{student.name}: {student.points}" for student in self._members)

    def disband(self):
        self._members.clear()
        self._active = False

report = Report("Robot design")
report.add_section("Testing", "The robot completed three trials.")
report.add_section("Evaluation", "Alignment needs improvement.")
print(report.section_titles())

sam = Student("Sam")
robotics = Club("Robotics", [sam])
coding = Club("Coding", [sam])
sam.award_point()
print(robotics.member_summaries())
print(coding.member_summaries())

robotics.disband()
print(sam.name, sam.points)
print(coding.member_summaries())
report.delete()
try:
    print(report.section_titles())
except ValueError:
    print("Report and its sections are no longer active")

After robotics.disband(), Sam still has one point and Coding can still list Sam. After report.delete(), report.section_titles() raises ValueError, which the demonstration catches to print a clear message. The difference follows the designed ownership rules.

17 | DELETING A NAME IS NOT DELETING AN OBJECT

sam = Student("Sam")
club = Club("Robotics", [sam])
alias = club
del club
print(alias.member_summaries())
# ('Sam: 0',)

In Python, del club removes that name. alias still refers to the same Club object, so the object remains reachable and usable. It has not been disbanded. Likewise, del report is not automatically the same application action as report.delete().

Object memory management is separate from modelled lifetime. Python implementations may reclaim unreachable objects at different times. Java also reclaims unreachable objects through garbage collection without promising immediate collection at a chosen statement.

Composition describes ownership and dependent lifetime in the system being modelled. It is not a universal promise that one line instantly erases bytes from memory.

18 | DESIGN THE LIFETIME RULE, DO NOT ASSUME IT

Our composition example creates parts internally, keeps them behind Report operations and explicitly removes active content when the report is deleted. These choices work together. Merely using new or calling a constructor inside another constructor does not prove that a whole owns the part.

If code exposed a mutable _ReportSection object to other owners, those references could keep it reachable or permit inconsistent edits. Python underscores rely on discipline; they do not prevent deliberate access. Java private fields restrict direct access, but methods could still leak references if designed carelessly.

In a database-backed app, composition might also require deleting dependent rows or marking them inactive in the same transaction. Clearing an in-memory list alone would not delete records already stored in a database.

19 | JAVA: THE SAME RELATIONSHIPS

The Java program below uses a private nested ReportSection class and a private section list to express internal ownership. Club receives independently created Student objects. new ArrayList<>(members) copies the list structure while retaining the student references.

import java.util.ArrayList;
import java.util.List;

class Report {
    private static class ReportSection {
        private final String title;
        private final String text;
        ReportSection(String title, String text) {
            this.title = title;
            this.text = text;
        }
    }
    private final List<ReportSection> sections = new ArrayList<>();
    private boolean active = true;

    public void addSection(String title, String text) {
        ensureActive();
        sections.add(new ReportSection(title, text));
    }
    public List<String> sectionTitles() {
        ensureActive();
        List<String> result = new ArrayList<>();
        for (ReportSection section : sections) {
            result.add(section.title);
        }
        return result;
    }
    private void ensureActive() {
        if (!active) throw new IllegalStateException("Report has been deleted");
    }
    public void delete() {
        sections.clear();
        active = false;
    }
}

class Student {
    private final String name;
    private int points = 0;
    public Student(String name) { this.name = name; }
    public void awardPoint() { points++; }
    public String summary() { return name + ": " + points; }
}

class Club {
    private final List<Student> members;
    private boolean active = true;
    public Club(List<Student> members) {
        this.members = new ArrayList<>(members);
    }
    public List<String> memberSummaries() {
        if (!active) throw new IllegalStateException("Club has been disbanded");
        List<String> result = new ArrayList<>();
        for (Student student : members) result.add(student.summary());
        return result;
    }
    public void disband() {
        members.clear();
        active = false;
    }
}

public class RelationshipsExample {
    public static void main(String[] args) {
        Report report = new Report();
        report.addSection("Testing", "Three trials completed.");
        System.out.println(report.sectionTitles());
        Student sam = new Student("Sam");
        Club robotics = new Club(List.of(sam));
        Club coding = new Club(List.of(sam));
        sam.awardPoint();
        System.out.println(robotics.memberSummaries());
        robotics.disband();
        System.out.println(sam.summary());
        System.out.println(coding.memberSummaries());
        report.delete();
        try {
            System.out.println(report.sectionTitles());
        } catch (IllegalStateException error) {
            System.out.println("Report and its sections are no longer active");
        }
    }
}

Save this as RelationshipsExample.java and run main in a Java 11 or later project. List.of is available in these versions. In the code, static on the nested ReportSection class means it does not require an implicit outer Report reference; it does not make all section objects shared.

delete and disband are ordinary methods implementing application rules. They do not call a memory destructor or guarantee when garbage collection happens. The returned lists contain strings, so modifying those returned lists cannot edit the stored components or memberships.

20 | DELEGATION: LET A COMPONENT DO ITS JOB

Relationships become useful when objects collaborate. Delegation means asking another object to perform part of a task. A robot controller can ask its motor component to spin instead of containing every low-level motor instruction itself.

class Motor:
    def __init__(self):
        self.speed = 0

    def set_speed(self, speed):
        self.speed = speed

class Robot:
    def __init__(self):
        self._motor = Motor()

    def drive(self, speed):
        self._motor.set_speed(speed)

robot = Robot()
robot.drive(40)

This small simulation delegates drive behaviour to a Motor component. Whether Motor is composition-owned depends on the model’s ownership and lifetime rules. Real physical motors can be removed and reused, so a physical inventory system might model the relationship differently from this internal software component.

Delegation explains how objects work together; composition and aggregation explain the whole–part relationship and ownership expectations.

21 | THE SAME NOUNS CAN HAVE DIFFERENT RELATIONSHIPS

Scenario rule Suitable interpretation Why
A report section exists only within its report and is removed with it Composition The section is an owned dependent part
An article is stored in a shared library and linked from several reports Aggregation, if reports group articles The article has an independent identity and lifetime
A team groups students who also exist in the school register Aggregation Removing the team should not remove students
A teacher comments on a report without owning it Association Collaboration need not imply a whole–part relationship

Do not choose solely from a familiar noun pair such as car and engine or school and student. Ask what this application considers an independent entity, who owns each part and what deleting the whole is supposed to do.

The requirement should justify the relationship. If the scenario does not specify ownership, state a reasonable assumption and explain how it leads to your choice.

22 | BENEFITS OF BUILDING WITH COMPONENT OBJECTS

Smaller classes can keep responsibilities focused: a section stores report content, while Report manages the collection and lifecycle. Independent Student objects can be reused across clubs instead of copying student state into every club.

This separation can improve maintenance because a change has a clear home. It can also improve testing: test Student point updates separately, then test that Club refers to the same student correctly. For an owned part, test the whole’s public operations and lifetime rules.

The common benefit is assembling a larger object from smaller useful pieces. The different ownership rules tell us how tightly those pieces belong to the whole.

23 | TRADE-OFFS AND SHARED MUTABLE STATE

Composition gives the whole clear control of owned parts, but creates stronger lifecycle coupling. A component designed only for one owner may be harder to reuse directly elsewhere. Keep useful component responsibilities focused while preserving the owner’s rules.

Aggregation supports reuse of independent objects, but shared mutable state needs care. When Sam’s points change, every club referring to Sam sees the new value. That is correct here, but a historical award certificate might need a saved snapshot rather than a live student reference.

Neither relationship automatically provides security, synchronisation or database transactions. Those concerns need their own designs. Choose live references or snapshots according to what the data is meant to represent.

24 | TEST THE RELATIONSHIPS, NOT JUST THE OUTPUT

report = Report("Design")
report.add_section("Testing", "Three successful runs")
assert report.section_titles() == ("Testing",)
report.delete()
try:
    report.section_titles()
except ValueError:
    pass
else:
    raise AssertionError("Deleted report should be inactive")

sam = Student("Sam")
robotics = Club("Robotics", [sam])
coding = Club("Coding", [sam])
robotics.disband()
sam.award_point()
assert sam.points == 1
assert coding.member_summaries() == ("Sam: 1",)

The first group tests the report’s owner-managed lifetime. The second tests student independence and sharing: closing one club must not remove the student or break the other club. Run this after the complete class definitions.

Also create two reports and add sections to only one. If both unexpectedly change, the section list may have been placed at class level and shared by mistake. Each report needs its own instance list.

25 | COMMON MISTAKES

Mistake Correction
Put the UML diamond at the part Place it at the containing whole
Say composition is the same as inheritance Composition is whole–part; inheritance is specialisation
Assume every stored reference proves aggregation Check the model’s ownership and independence rules
Say del club destroys Sam Deleting a name is separate from object and domain lifetime
Assume a shallow list copy duplicates students The new list still refers to the same Student objects
Share one composition part between two owners Preserve exclusive ownership in the model
Classify only from familiar nouns Use the scenario requirements and state assumptions

26 | EXPLAIN THE CHOICE WITH A REASON

For composition, make the lifecycle link explicit: Report creates and owns its sections, so those sections are not independently managed resources. When the report is deleted in the application, its sections are removed as active content, therefore their modelled lifetime depends on the report.

For aggregation, explain independence: Club groups references to students who already exist. Disbanding the club removes the grouping, but students can still be used by the school and other clubs, because their lifetime is not owned by that club.

Your design task is a Quiz that owns its question instances and a StudyGroup that groups independent Student objects. Explain creation, sharing, removal and UML notation for both. In the next lesson, design patterns show reusable approaches to recurring object-oriented design problems.

MATCH THE RELATIONSHIP IDEA

Terminology

Terminology

Composition

A strong whole–part relationship with exclusive ownership and dependent modelled lifetime.

Aggregation

A whole–part relationship whose components can exist and function independently of the whole.

Association

A general relationship or collaboration between objects.

Whole

The object that contains or groups the parts in a whole–part relationship.

Part

A component object contained or grouped by a larger object.

Component

A smaller object with a focused responsibility used in a larger design.

Ownership

Responsibility for managing an object and its lifecycle in the model.

Exclusive ownership

A composition part belongs to at most one composite owner at a time.

Modelled lifetime

The period in which an entity exists or remains active according to application rules.

Independent lifetime

An entity can remain meaningful and usable without a particular containing whole.

Object reference

A value providing access to an existing object.

Object identity

The fact that references refer to one particular object rather than merely equal data.

Alias

Another reference or name for the same object.

Shared reference

A reference to an object also reachable through another route.

Delegation

An object asks another object to perform part of its task.

Inheritance

An is-a relationship where a subclass specialises a superclass.

Has-a relationship

An object contains or refers to a part; ownership must still be specified.

Filled diamond

The UML composition marker placed at the whole end of the relationship.

Hollow diamond

The UML aggregation marker placed at the whole end of the relationship.

Multiplicity

A UML count describing how many related instances are permitted.

Shallow copy

A new container holding references to the same contained objects.

Snapshot

A saved view of values that does not automatically track later changes to the original objects.

Mutable state

Object data that can change after creation.

Encapsulation

Organising state and behaviour with suitable access boundaries.

Reference leak

Exposing an internal object reference in a way that can undermine intended ownership or control.

Garbage collection

Automatic reclamation of memory for objects that are no longer reachable, subject to runtime rules.

Reachability

Whether an object can still be accessed through live references.

Domain deletion

An application action removing or deactivating an entity according to system rules.

Lifecycle coupling

A dependency between the modelled lifetimes of related objects.

Modularity

Dividing a program into focused components with clear interactions.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. Which describe composition in the report model?
2. Which describe aggregation in the club model?
3. Which UML claims are correct?
4. What does list(members) do here?
5. After robotics.disband(), which remain true?
6. Which distinguish modelled deletion and memory management?
7. Which are good relationship justifications?
8. Which demonstrate delegation?
9. Which risks need attention?
10. Which tests match the model?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Define composition in an object-oriented class relationship.

2. Define aggregation in an object-oriented class relationship.

3. Compare composition and aggregation using the report and club examples.

4. Explain why inheriting Club from Student would be unsuitable.

5. Describe the UML notation for both relationships.

6. Trace Sam’s state after two clubs share Sam, Sam receives one point and Robotics disbands.

7. Explain why copying the membership list does not copy the students.

8. Explain why del club is not the same as disbanding the club.

9. Explain how composition can improve modularity.

10. Evaluate aggregation when several clubs share mutable Student objects.

11. Construct a design for a Quiz owning questions and a StudyGroup grouping students.

12. Explain why relationship choices depend on the scenario rather than just class names.

CONSTRUCT AND EXPLAIN | QUIZZES AND STUDY GROUPS

Construct a Quiz that creates and owns Question objects. Add a title-list operation and a delete operation that removes active questions and blocks further question access. Separately construct a StudyGroup that groups existing Student objects and can be disbanded without modifying them.

Reveal a design

Reuse the Report design with Quiz replacing Report and Question replacing the internal section. Create questions inside add_question rather than accepting a shared owned part. Return text snapshots rather than question objects. Reuse the Club design for StudyGroup, copying the membership container while retaining independent Student references.

Explain: quiz questions have dependent modelled lifetime because the quiz manages their creation and deletion. Students remain independently usable, therefore disbanding a study group must not delete them. Test that one student can remain in another group and that a deleted quiz rejects further question operations.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

Selections are kept while this page is open.

Workbook

Workbook

COMING SOON

The workbook for B3.2.4 Composition and Aggregation (HL) is coming soon. Complete the matching task and written questions in your exercise book.