0

I found the following two examples differentiating aggregation and composition in a java code
Composition

final class Car {

  private final Engine engine;

  Car(EngineSpecs specs) {
    engine = new Engine(specs);
  }

  void move() {
    engine.work();
  }
}

Aggregation

final class Car {

  private Engine engine;

  void setEngine(Engine engine) {
    this.engine = engine;
  }

  void move() {
    if (engine != null)
      engine.work();
  }
}

I have some doubts. I noticed the following points on these two
1 When two objects are aggregated, it looks similar to composition, the only
difference is that if the root object is destroyed, the other objects will not be destroyed.

  1. Could we then say that an aggregation is also a composition but not vice versa ?

  2. Since in aggregation a composition is involved, the only way for the objects to exist
    independently is to provide them from outside. Kind of like inject them rather then compose them
    from inside the root class. This sounds a lot like Dependency Injection principle.

Any comments on the above points or some more pointers ?

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
asha rani
  • 41
  • 6
  • https://stackoverflow.com/questions/885937/what-is-the-difference-between-association-aggregation-and-composition – VoiceOfUnreason Mar 17 '21 at 12:15
  • Also: No, "aggregate pattern", as understood in the literature of domain driven design, should not be understood as an expression of "aggregation". It's nature is close to that of composition. – VoiceOfUnreason Mar 17 '21 at 12:18
  • Thanks for the link. The aggregate looks much like Dependency Injection. Isn't it ? – asha rani Mar 17 '21 at 13:12

1 Answers1

0

Composition and aggregation are two types of association which is used to represent relationships between two classes.

In Aggregation, parent and child entity maintain Has-A relationship but both can also exist independently. We can use parent and child entities independently. Any modification in the parent entity will not impact the child entity or vice versa. In the UML diagram, aggregation is denoted by an empty diamond, which shows their obvious difference in terms of the strength of the relationship.

In Composition, the parent owns child entity so child entity can’t exist without parent entity. We can’t directly or independently access the child entity. In the UML diagram, the composition is denoted by a filled diamond.

For more info see here

Mohammad
  • 1,197
  • 2
  • 13
  • 30