Association, Composition & Aggregation
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
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.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.