What is the Difference Between Aggregation and Composition?

🆚 Go to Comparative Table 🆚

The main difference between aggregation and composition lies in the relationship between the parent and child objects, as well as the ownership and lifetime of the child objects. Here are the key differences between aggregation and composition:

  1. Relationship: Aggregation represents a "Has-A" relationship, where the parent object has a child object, but the child object can exist independently of the parent object. In composition, the child object cannot exist independently of the parent object, and the relationship is "part-of".
  2. Ownership: In composition, the parent object owns the child object, while in aggregation, the parent object does not own the child object.
  3. Lifetime: In aggregation, the child object has its own lifetime, while in composition, the child object's lifetime is tied to the parent object's lifetime.
  4. Examples: In aggregation, an example would be a class (parent) and a student (child). If the class is deleted, the students still exist. In composition, an example would be a house (parent) and a room (child). Rooms cannot exist without a house.
  5. UML Notation: In UML diagrams, aggregation is represented by an empty diamond, while composition is represented by a filled diamond.

In summary, aggregation is a weaker form of association, where the child object can exist independently of the parent object, while composition is a stronger form of association, where the child object cannot exist independently of the parent object.

Comparative Table: Aggregation vs Composition

Here is a table comparing the differences between aggregation and composition in UML:

Aggregation Composition
Aggregation is a type of association between two objects, where one object "has a" relationship with the other. Composition is a specific type of aggregation that implies ownership and a whole-part relationship between the objects.
Aggregation is indicated using a straight line with an empty arrowhead at one end. The composition is indicated using a straight line with a filled arrowhead at any one of the ends.
In an aggregation relationship, the objects can exist independently without the parent. In a composition relationship, the child object's lifecycle is dependent on the parent object, meaning that if the parent object is destroyed, the child object will also be destroyed.

In summary, aggregation and composition are both types of association relationships in UML, but they differ in the level of dependency between the objects and the way they are represented in a UML diagram. Aggregation represents a "has a" relationship with independence between the objects, while composition represents a whole-part relationship with a higher level of dependency.