Aggregation in JavaLast 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 ExampleConsider 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 AggregationIn the following example, the Circle class uses the Operation class through object reference to calculate the area. ExampleCompile and RunOutput:78.5 Why use Aggregation?The following are the reasons to use aggregation in Java:
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 AggregationIn 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. ExampleCompile and Run
111 varun
gzb UP india
112 arun
gno UP india
Next TopicMethod Overloading in java |
We request you to subscribe our newsletter for upcoming updates.