Understanding OOP Concepts: Association, Composition & Aggregation

Published on April 11, 2020 44 sec read

Association, Aggregation and Composition are terms that represent relationships among objects. They are very basic stuff of Object-Oriented Programming.

In this article, I’ll explain association, composition & aggregation. Let’s get started:

Table of Contents

  1. Association
  2. Composition
  3. Aggregation

Association

Association is a relationship between two objects. Association can be one-to-one, one-to-many, many-to-one, many-to-many. Composition and aggregation are two types of association.

Example: A Car and a Engine are having an association.

Composition

Composition is a strong association. An association is said to composition if an object owns another object and another object cannot exist without the owner object.

Example: Car class contains Engine. Engine cannot exist without a Car. There exists composition between Car and Engine.

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

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

// Engine Object
class Engine {}

Aggregation

Aggregation is a weak association. An association is said to be aggregation if both objects can exist independently.

Example: A Team has 0 or more players. A Player can be in a Team or not. There exists aggregation between Team and Player.

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

   Team() {
      players = new Player();
   }
}

// Player Object
class Player {}
The article is over. Thanks for reading. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development. If you enjoy my content, please consider supporting what I do!

Follow Buy me a coffeeBuy me a coffee

Leave a Reply

Your email address will not be published. Required fields are marked *