Aggregation in Java

Last Updated : 2 Jan 2026

Aggregation in Java represents a HAS-A relationship where one class contains a reference to another class. In this chapter, we will learn about the aggregation with definition and real-life examples.

What Is Aggregation in Java?

If a class has a reference to another class (i.e., an entity reference), it is known as Aggregation. Aggregation represents a HAS-A relationship, where one object uses another object as part of its functionality.

Understanding Aggregation with an Example

Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one more object named address, which contains its own informations such as city, state, country, zipcode etc. as given below.

In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.

Example of Aggregation

In the following example, the Circle class uses the Operation class through object reference to calculate the area.

aggregation example

Example

Compile and Run
Output:78.5

Why use Aggregation?

The following are the reasons to use aggregation in Java:

  • Code Reusability: Aggregation is helpful to reuse the code as it allows one class to reuse the functionality of another class without inheriting it.
  • Better Design: It is useful when classes are related through a HAS-A relationship, not an IS-A relationship.
Note: 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.

Real-Time Example of Aggregation

In this example, Employee has an object of Address, address object contains its own informations such as city, state, country etc. In such case relationship is Employee HAS-A Address.

Example

Compile and Run
       111 varun
       gzb UP india
       112 arun
       gno UP india