Home › Theme B › B3 › B3.2 › B3.2.4

B3.2.4 Composition and aggregation

HL onlyCommand term: Explain

1. Who survives? The lifecycle stepper

A Library creates its own shelves (composition) but is given its members (aggregation). Step through, then delete the library and see which parts disappear with it.

2. Draw the right line: UML relationships

Choose the relationship for each pair and watch the UML diagram change. A hollow diamond means aggregation, a filled diamond means composition, and the diamond sits next to the whole.

Pair:
Choose a relationship.

3. Build a car from parts: composition versus inheritance

Choose the parts. With composition, one Car class is built from component objects and can even swap a part while running. With inheritance, every combination needs its own subclass.

Engine
Wheels   Extras

4. Flip-card deck

Click to flip. Say the answer before you flip.

5. Composition, aggregation or inheritance?

Classify each relationship. Ask: is it is-a or has-a? If has-a, can the part live on its own? Streaks of 3+ score double.

Round 0/10Score 0Streak 0Best 0
Press start!

6. 45-second speed round: does the part survive?

After the code runs, can any variable still reach the part object? A wrong answer costs 3 seconds.

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 7, task 4 (HL). ShelfWise now runs several branch libraries. Each branch owns its shelves: they are created with the branch and disappear when it closes (composition). Members are different: one person can belong to the city library and the school library at the same time, and stays a member of the school when the city branch closes (aggregation).

Expected output

Until the TODOs are done, the first test stops with an AttributeError.

2 1 ['Ana', 'Ben'] ['Ana'] [] [] Ana ['Ana'] False

Think about it

  • Why does the Library create the Shelf objects itself instead of receiving them as parameters?
  • Why must add_member() receive an existing Member object instead of creating a new one from a name?
  • The shelves are stored in a private attribute and never returned. How does that protect the composition?

Check my code

    Next (B3.2.5): design patterns: a single shared catalogue (singleton), one place to create items (factory) and notifying members when a book comes back (observer).

    Practical tasks

    Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

    Task 1: A car has an engine (composition)

    Write Engine (horsepower, running, start(), stop()) and Car that creates its own Engine in its constructor. Car.drive() returns a message that depends on whether the engine is running. Explain why a Car is not a subclass of Engine.

    Starter file (write your code where it says pass # your code here):

    File: b3_2_4_average.py
    class Engine:
        pass  # your code here
    
    class Car:
        pass  # your code here
    
    # ---- tests ----
    c = Car("BYD Seal", 308)
    print(c.drive())
    c.engine.start()
    print(c.drive())
    

    Expected output when your code is correct:

    BYD Seal: start the engine first
    BYD Seal drives with 308 hp
    Hint
    Ask: is a car a kind of engine, or does a car contain one?
    Model solution

    A car has an engine; it is not an engine. Inheritance models 'is a'; composition models 'has a'. Here the Engine is created and owned by the Car, so it is composition.

    File: b3_2_4_average_solution.py
    class Engine:
        def __init__(self, hp):
            self.hp = hp
            self.running = False
        def start(self):
            self.running = True
        def stop(self):
            self.running = False
    
    class Car:
        def __init__(self, model, hp):
            self.model = model
            self.engine = Engine(hp)
        def drive(self):
            if not self.engine.running:
                return f"{self.model}: start the engine first"
            return f"{self.model} drives with {self.engine.hp} hp"
    
    # ---- tests ----
    c = Car("BYD Seal", 308)
    print(c.drive())
    c.engine.start()
    print(c.drive())
    
    Moderate

    Task 2: Teams and players (aggregation)

    Players exist independently and can move between teams. Write Player(name, rating) and Team(name) with sign(player) (a player can be in only one team, so sign them out of any old team), release(player) and strength() (the average rating). Show that releasing a player does not delete them.

    Starter file (write your code where it says pass # your code here):

    File: b3_2_4_moderate.py
    class Player:
        pass  # your code here
    
    class Team:
        pass  # your code here
    
    # ---- tests ----
    ana, ben, cai = Player("Ana", 82), Player("Ben", 75), Player("Cai", 90)
    red, blue = Team("Red"), Team("Blue")
    for p in (ana, ben): red.sign(p)
    blue.sign(cai)
    print(red.strength(), blue.strength())
    blue.sign(ana)
    print([p.name for p in red.players], [p.name for p in blue.players], ana.team.name)
    red.release(ben)
    print(ben.name, ben.team, red.strength())
    

    Expected output when your code is correct:

    78.5 90.0
    ['Ben'] ['Cai', 'Ana'] Blue
    Ben None 0
    Hint
    In aggregation the part (player) is created outside the whole (team) and outlives it.
    Model solution
    File: b3_2_4_moderate_solution.py
    class Player:
        def __init__(self, name, rating):
            self.name = name
            self.rating = rating
            self.team = None
    
    class Team:
        def __init__(self, name):
            self.name = name
            self.players = []
    
        def sign(self, player):
            if player.team is not None:
                player.team.release(player)
            self.players.append(player)
            player.team = self
    
        def release(self, player):
            if player in self.players:
                self.players.remove(player)
                player.team = None
    
        def strength(self):
            if not self.players:
                return 0
            return round(sum(p.rating for p in self.players) / len(self.players), 1)
    
    # ---- tests ----
    ana, ben, cai = Player("Ana", 82), Player("Ben", 75), Player("Cai", 90)
    red, blue = Team("Red"), Team("Blue")
    for p in (ana, ben): red.sign(p)
    blue.sign(cai)
    print(red.strength(), blue.strength())
    blue.sign(ana)
    print([p.name for p in red.players], [p.name for p in blue.players], ana.team.name)
    red.release(ben)
    print(ben.name, ben.team, red.strength())
    
    Challenging

    Task 3: School, departments and teachers

    Build a three-level model: a School owns its Departments (composition: created by school.add_department(name), and deleted with the school), while Teachers are created separately and assigned to departments (aggregation). Write school.find_teacher(name), school.headcount() (unique teachers, since a teacher can be in two departments) and school.close_department(name) that removes it but leaves its teachers existing. Explain which relationships are composition and which are aggregation.

    Starter file (write your code where it says pass # your code here):

    File: b3_2_4_challenging.py
    class Teacher:
        pass  # your code here
    
    class Department:
        pass  # your code here
    
    class School:
        pass  # your code here
    
    # ---- tests ----
    s = School("Lakeside IB")
    cs, ma = s.add_department("CS"), s.add_department("Maths")
    raut, li, wu = Teacher("Mr Raut"), Teacher("Ms Li"), Teacher("Dr Wu")
    cs.assign(raut); cs.assign(wu); ma.assign(li); ma.assign(wu)
    print(s.find_teacher("Dr Wu"), s.headcount())
    s.close_department("CS")
    print(list(s.departments), s.headcount(), raut.name)
    

    Expected output when your code is correct:

    ['CS', 'Maths'] 3
    ['Maths'] 2 Mr Raut
    Hint
    Count unique teachers with a set.
    Model solution

    School ◆── Department is composition: departments are created by the school and have no meaning without it. Department ◇── Teacher is aggregation: teachers exist independently, can belong to several departments, and survive when a department closes.

    File: b3_2_4_challenging_solution.py
    class Teacher:
        def __init__(self, name):
            self.name = name
    
    class Department:
        def __init__(self, name):
            self.name = name
            self.teachers = []
    
        def assign(self, teacher):
            if teacher not in self.teachers:
                self.teachers.append(teacher)
    
    class School:
        def __init__(self, name):
            self.name = name
            self.departments = {}
    
        def add_department(self, name):
            d = Department(name)
            self.departments[name] = d
            return d
    
        def find_teacher(self, name):
            found = []
            for d in self.departments.values():
                for t in d.teachers:
                    if t.name == name:
                        found.append(d.name)
            return found
    
        def headcount(self):
            return len({id(t) for d in self.departments.values() for t in d.teachers})
    
        def close_department(self, name):
            return self.departments.pop(name, None)
    
    # ---- tests ----
    s = School("Lakeside IB")
    cs, ma = s.add_department("CS"), s.add_department("Maths")
    raut, li, wu = Teacher("Mr Raut"), Teacher("Ms Li"), Teacher("Dr Wu")
    cs.assign(raut); cs.assign(wu); ma.assign(li); ma.assign(wu)
    print(s.find_teacher("Dr Wu"), s.headcount())
    s.close_department("CS")
    print(list(s.departments), s.headcount(), raut.name)
    

    Learning objectives

    By the end of this page you should be able to:

    1. Explain how objects can be designed from smaller component objects (has-a relationships).
    2. Distinguish between aggregation (the parts can exist independently of the whole) and composition (the parts are created, owned and destroyed with the whole).
    3. Represent association, aggregation and composition on UML class diagrams with the correct symbols and multiplicities.
    4. Construct classes that use composition and aggregation, including delegating work to component objects.
    5. Evaluate composition against inheritance as a way of reusing code.

    Building objects from objects

    Inheritance models is-a. Many relationships are has-a instead: a car has an engine, a library has members. The containing object (the whole) holds references to component objects (the parts) and delegates work to them: car.start() calls self.engine.start().

    AggregationComposition
    Relationshiphas-a (weak)part-of (strong)
    Who creates the part?usually created elsewhere and passed increated by the whole, usually in its constructor
    Can the part be shared?yes: one member, many librariesno: a room belongs to one house
    If the whole is destroyedthe parts carry onthe parts are destroyed too
    Couplingloosetight
    UMLhollow diamond at the wholefilled diamond at the whole
    ExamplesTeam and Player; Playlist and Song; Department and ProfessorHouse and Room; Order and OrderLine; Book and Chapter

    In code

    class Library:
        def __init__(self, name, labels):
            self.__shelves = [Shelf(l) for l in labels]   # composition: created and owned here
            self.__members = []                           # aggregation: filled from outside
    
        def add_member(self, member):                     # an existing Member is passed in
            self.__members.append(member)
    
    ana = Member("Ana")                                   # Ana exists before any library
    city = Library("City", ["A", "B"])
    city.add_member(ana)
    del city                                              # the shelves go; Ana is still here

    In Python and Java, an object is removed by the garbage collector when no references to it remain. Composition is therefore partly a design rule: keep the parts private, create them inside the whole, and never hand them out, so nothing else can keep them alive.

    UML symbols

    • Association: a plain line (a Teacher teaches Students).
    • Aggregation: a line with a hollow diamond at the whole (Team ◇—— Player).
    • Composition: a line with a filled diamond at the whole (House ◆—— Room). The multiplicity at the whole is always 1.
    • Inheritance: a hollow triangle pointing at the superclass.

    Favour composition over inheritance?

    • Flexibility: parts can be swapped, even at run time (a new engine); an inherited parent is fixed.
    • No class explosion: 3 engines × 2 wheel types × GPS or not needs 12 subclasses, but only 6 component classes and 1 Car.
    • Looser coupling: the Car uses an engine only through its public methods.
    • Inheritance is still right for genuine is-a relationships that share behaviour and need polymorphism.

    Use the 中文 button at the top to show or hide the Chinese terms.

    Term中文Meaning

    Choose an answer. You get instant feedback.

    Score: 0 /

    Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.

    1. Distinguish between aggregation and composition, using an example of each. [4]

    Aggregation: a has-a relationship in which the part can exist independently of the whole / can be shared [1], e.g. a Team and its Players, who exist before and after the team [1]. Composition: a strong relationship in which the part is created and owned by the whole and cannot exist without it [1], e.g. a House and its Rooms, which are destroyed with the house [1].

    2. A university is made up of departments, which close if the university closes. Each department employs professors, who may move to another university. Draw a UML class diagram showing these relationships, with multiplicities. [4]

    Three classes University, Department, Professor [1]; filled diamond (composition) at University on the University–Department line [1]; hollow diamond (aggregation) at Department on the Department–Professor line [1]; sensible multiplicities, e.g. University 1 —— 1..* Department, Department 0..* —— 0..* Professor [1].

    3. Construct a class Car composed of an Engine that is created inside the Car's constructor. Car.start() should delegate to the engine's start() method. [4]

    Engine class with a start() method [1]; Car constructor creates a new Engine and stores it in a (private) attribute [1]; Car.start() calls the engine's start() [1]; returns/prints its result, with no Engine passed in from outside [1].
    class Engine:
        def start(self):
            return "engine running"
    
    class Car:
        def __init__(self):
            self.__engine = Engine()       # composition
        def start(self):
            return self.__engine.start()   # delegation

    4. Explain why a designer might choose composition rather than inheritance to reuse the code of an existing class. [3]

    Composition models has-a relationships where inheritance (is-a) would be inaccurate [1]; components can be swapped / combined at run time, avoiding a separate subclass for every combination [1]; the classes are more loosely coupled because the whole uses only the part's public interface, so changes to the part's internals do not affect it [1].

    5. State whether each relationship is aggregation, composition or inheritance: (a) Playlist and Song; (b) Order and OrderLine; (c) Cat and Animal. [3]

    (a) aggregation: songs exist without the playlist [1]; (b) composition: order lines belong to one order and are deleted with it [1]; (c) inheritance: a cat is an animal [1].

    6. In a composition relationship, outline what happens to the Room objects when their House object is deleted, and how the House class should be written to guarantee this. [3]

    The Rooms are destroyed / garbage collected with the House, since nothing else refers to them [1]; the House should create its Rooms itself (e.g. in its constructor) [1] and keep them private without returning references to outside code [1].