Association, Composition and Aggregation in Java

Java Programming Java8Object Oriented Programming

Association

Association refers to the relationship between multiple objects. It refers to how objects are related to each other and how they are using each other's functionality. Composition and aggregation are two types of association.

Composition

The composition is the strong type of association. An association is said to composition if an Object owns another object and another object cannot exist without the owner object. Consider the case of Human having a heart. Here Human object contains the heart and heart cannot exist without Human.

Aggregation

Aggregation is a weak association. An association is said to be aggregation if both Objects can exist independently. For example, a Team object and a Player object. The team contains multiple players but a player can exist without a team.

Example of Composition

//Car must have Engine
public class Car {
   //engine is a mandatory part of the car
   private final Engine engine;

   public Car () {
      engine = new Engine();
   }
}

//Engine Object
class Engine {}

Example of Aggregation

//Team
public class Team {      
   //players can be 0 or more
   private List players;

   public Car () {
      players = new ArrayList();
   }
}
//Player Object
class Player {}
raja
Published on 20-Jul-2018 11:51:29
Advertisements