Sobes.tech
Junior — Middle

What are the differences between aggregation and composition relationships in object-oriented programming?

sobes.tech AI

Answer from AI

Aggregation and composition are two types of relationships between objects in OOP that describe how objects are connected.

  • Aggregation is a "has-a" relationship where one object contains another, but the lifecycle of the contained object does not depend on the container. The nested object can exist independently.

  • Composition is a stronger form of aggregation where the nested object fully belongs to the container and does not exist separately. If the container is destroyed, the nested object is also destroyed.

Example:

class Engine {}

// Aggregation: Car has Engine, but Engine can exist independently
class Car {
    var engine: Engine?
}

// Composition: House consists of Rooms, rooms do not exist without the house
class Room {}

class House {
    var rooms: [Room] = []
    init() {
        rooms = [Room(), Room()]
    }
}

In composition, objects are tightly linked and managed together, while in aggregation, the connection is weaker.