Aggregation in Java

Shraddha Shinde
2 min readApr 1, 2020

When you are writing a Java program, if you want to link one class to another using its reference, you can make use of Aggregation in Java. So, let’s learn how Aggregation works in Java.

What is Aggregation?

Aggregation is an association represents a part of a whole relationship where a part can exist without a whole. It has a weaker relationship.

It is a specialised form of Association where all object has their own life cycle but there is ownership. This represents “whole-part or a-part-of” relationship.

Let’s take an example of the relationship between Department and Teacher. A Teacher may belong to multiple departments. Hence Teacher is a part of multiple departments. But if we delete a Department, Teacher Object will not destroy.

Key Points

  • It represents the Has-A relationship.
  • It is a unidirectional association i.e. a one-way relationship. For example, the department can have students but vice versa is not possible and thus unidirectional in nature.
  • In Aggregation, both the entries can survive individually which means ending one entity will not affect the other entity.

Now you might have this question. Why exactly should you use this Aggregation in Java?

Answer is For Code Reusability.

Simple Example of Aggregation

When use Aggregation?

  • Code reuse is also best achieved by aggregation when there is no is-a relationship.
  • Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice.

Implementation

Let’s take an example of Line item and their Products. If line-item HAS-A product, then a line item is a whole and product is a part.

If a line item is deleted, then corresponding product needs not to be deleted.

Step 1: Create a Product class.

Step 2: This is LineItem class, which HAS-A aggregation association with Product class. That means, if you delete LineItem, then associated Product can exist.

Step 3: Let’s test an Aggregation.

Aggregation Vs Composition

Authors of the blog :

Shraddha Shinde
Priyanka patil
Priyanka Salunke
Vaishnavi Nadargi

--

--