Aggregation vs Composition in UML

Tue, Sep 12, 2023 2-minute read

In object-oriented design and programming, the concepts of aggregation and composition are used to establish relationships between classes. These relationships are often depicted in UML (Unified Modeling Language) diagrams and implemented in programming languages like Java. Let’s delve into both concepts and see how they differ.

UML Representation

  • Aggregation: In UML, an aggregation relationship is depicted by a hollow diamond at the parent class end, pointing towards the child class.
  • Composition: In UML, a composition relationship is depicted by a filled diamond at the parent class end, pointing towards the child class.

Java Representation

In Java, both aggregation and composition can be implemented by using instance variables that refer to other objects.

Aggregation Example in Java:

class Engine {
    // Engine properties and methods
}

class Car {
    Engine carEngine;  // Aggregation

    Car(Engine engine) {
        this.carEngine = engine;
    }

    // Car properties and methods
}

Composition Example in Java:

class Wheel {
    // Wheel properties and methods
}

class Car {
    Wheel carWheel;  // Composition

    Car() {
        this.carWheel = new Wheel();  // Wheel is created when a new Car is created
    }

    // Car properties and methods
}

Key Differences

  1. Lifetime Dependency:

    • Aggregation: Child can exist independently of the parent.
    • Composition: Child cannot exist independently of the parent.
  2. Ownership:

    • Aggregation: Parent and child have a “Has-A” relationship, but the parent does not have full control over the lifecycle of the child.
    • Composition: Parent and child also have a “Has-A” relationship, but the parent fully owns the child and controls its lifecycle.
  3. Multiplicity:

    • Aggregation: Usually used when there is a one-to-many relationship between the parent and the child, but it’s not strictly required.
    • Composition: Typically used in one-to-one relationships, though not strictly so.
  4. Immutability:

    • Aggregation: Usually, the child can be reassigned to another parent.
    • Composition: Usually, the child cannot be reassigned to another parent.
  5. Deletion Propagation:

    • Aggregation: Deleting the parent does not necessarily mean the child will be deleted.
    • Composition: Deleting the parent will result in the deletion of the child as well.
  6. Flexibility:

    • Aggregation: More flexible but less strict in structure.
    • Composition: Less flexible but provides a more rigid structure.

Understanding these differences is crucial for effective object-oriented design and can lead to more maintainable and understandable code.