Lecture 12 – Composition and Aggregation

Understand Composition and Aggregation in Object-Oriented Programming. Learn the “has-a” relationship, difference between inheritance and composition, and explore real-world examples like Car and Engine in C++ and Java.

Introduction

So far, we’ve learned about Inheritance (the is-a relationship) where a class derives properties from another.
But sometimes, an object doesn’t inherit another; it simply uses another.

That’s where Composition and Aggregation come in.

Definition:

Composition and Aggregation represent a “has-a” relationship between two classes one class contains or owns another class’s object.

The “has-a” Relationship

In Object-Oriented Programming, a “has-a” relationship means one class contains another as a member object.

Examples in real life:

  • A Car has an Engine
  • A Library has many Books
  • A Department has Employees*

Here is our recent lecture, you can revise it and do focus if you skipped it:
Lecture# 11: Abstract Class and Interface.

Composition (Strong Relationship)

In Composition, one class cannot exist without the other.
If the container object is destroyed, the contained object also dies.

Example:
If a Car is destroyed, its Engine is also destroyed.

Example (C++ – Composition):

#include <iostream>
using namespace std;

class Engine {
public:
    void start() {
        cout << "Engine started." << endl;
    }
};

class Car {
private:
    Engine engine;  // Composition (Car owns Engine)
public:
    void startCar() {
        engine.start();
        cout << "Car is running." << endl;
    }
};

int main() {
    Car myCar;
    myCar.startCar();
}

Explanation:

  • Car has an Engine.
  • The Engine object is created automatically inside Car.
  • If Car is destroyed, Engine is also destroyed.

Example (Java – Composition):

class Engine {
    void start() {
        System.out.println("Engine started.");
    }
}

class Car {
    private Engine engine = new Engine(); // Composition

    void startCar() {
        engine.start();
        System.out.println("Car is running.");
    }
}

public class Main {
    public static void main(String[] args) {
        Car c = new Car();
        c.startCar();
    }
}

The Engine belongs entirely to the Car this is Composition.

Aggregation (Weak Relationship)

In Aggregation, one class uses another class, but both can exist independently.

Example:
A Department has Teachers, but if the department closes, the teachers still exist.

Example (C++ – Aggregation):

#include <iostream>
using namespace std;

class Teacher {
public:
    string name;
    Teacher(string n) : name(n) {}
};

class Department {
private:
    Teacher* teacher; // Aggregation (Pointer reference)
public:
    Department(Teacher* t) : teacher(t) {}
    void showTeacher() {
        cout << "Teacher: " << teacher->name << endl;
    }
};

int main() {
    Teacher t1("Mr. Ali");
    Department d(&t1);
    d.showTeacher();
}

Explanation:

  • The Teacher exists outside of Department.
  • If Department is destroyed, Teacher still exists weak relationship.

Example (Java – Aggregation):

class Teacher {
    String name;
    Teacher(String name) {
        this.name = name;
    }
}

class Department {
    Teacher teacher; // Aggregation
    Department(Teacher teacher) {
        this.teacher = teacher;
    }

    void showTeacher() {
        System.out.println("Teacher: " + teacher.name);
    }
}

public class Main {
    public static void main(String[] args) {
        Teacher t = new Teacher("Mr. Ali");
        Department d = new Department(t);
        d.showTeacher();
    }
}

The Teacher is passed as a reference Department doesn’t own it fully.

Composition and Aggregation

Difference Between Inheritance and Composition

FeatureInheritanceComposition
Relationship“is-a”“has-a”
ReuseInherits propertiesUses existing classes
LifetimeChild depends on parentComposed object dies with main object
ExampleCar extends VehicleCar has Engine
Code ChangeAffects subclassOnly affects owning class

Difference Between Composition and Aggregation

FeatureCompositionAggregation
OwnershipStrong – owned completelyWeak – shared or referenced
LifetimeDependentIndependent
ExampleCar and EngineDepartment and Teacher
Object CreationInside the classPassed from outside
Your upcoming lecture:
Lecture 13 – Exception Handling

Real-World Analogy

  • Composition: A human has a heart. Without the human, the heart cannot function alone.
  • Aggregation: A student has a teacher, but both can exist separately.

Summary of Lecture 12

ConceptRelationshipExample
CompositionStrong “has-a”CarEngine
AggregationWeak “has-a”DepartmentTeacher
Inheritance“is-a”DogAnimal
Positive Thought for Students

“Composition teaches teamwork strong when together, independent when needed. Build your code like relationships: meaningful and balanced.”

People also ask:

What is composition in object-oriented programming?

Composition is a strong relationship where one class owns another, and the contained object cannot exist without the owner.

What is aggregation, and how is it different from composition?

Aggregation is a weaker relationship where one class references another, but the referenced object can exist independently of the owner.

When should I use composition or aggregation?

Use composition when one object’s lifecycle depends on another, and aggregation when objects can exist separately but still need to interact.

Leave a Reply

Your email address will not be published. Required fields are marked *