Association, Composition and Aggregation - Yash-777/LearnJava GitHub Wiki

Association, Composition and Aggregation

Association

Association is relation between two separate classes which establishes through their Objects. Association can be one-to-one, one-to-many, many-to-one, many-to-many. In Object-Oriented programming, an Object communicates to other Object to use functionality and services provided by that object. Composition and Aggregation are the two forms of association.

Aggregation vs Composition
  • Dependency: Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist. whereas Composition implies a relationship where the child cannot exist independent of the parent. Example: Human and heart, heart don’t exist separate to a Human
  • Type of Relationship: Aggregation relation is “has-a” and composition is “part-of” relation.
  • Type of association: Composition is a strong Association whereas Aggregation is a weak Association.

It is a special form of Association is which represents Has-A relationship.

Aggregation

final class Car {

  private Engine engine;

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

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

Composition

final class Car {

  private final Engine engine;

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

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