Aggregation in Java

tutorial and example
tutorial and example

Aggregation is a special form of association. Aggregation is usedwhen we need to use property and behaviour of a class without modifying it in the class. Aggregation is also used to achieve code reusability.

  • We have two types of relationships one is HAS A and other is IS A relationship and Aggregation represents IS A relationship.
  • It is a special form of association i.e unidirectional association. To understand it, let’s take an example: There is an officer and a no. of employees are working for him. Then we can say Officer ‘HAS A ‘employee working for him but vice versa is not true.
  • In aggregation both the entity survive individually. If we end one entity that doesnot affect the other entity.

Example:

Output:

Example explanation:

In this example, there is a company let’s say ABC which has no. of officers like Sachin sir, Ashish sir. Every officer has no. of employees working for him. So, we make a company class which has a reference to Object or no. of Objects (i.e. List of Objects) of the Officer class. That means Company class is associated with Officerclass through its Object(s). And Officer class has also a reference to Object or Objects (i.e. List of Objects) of Employee class means it is associated with Employee class through its Object(s).

Let’s see diagrammatically what happened in this example: