Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.
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.
Why use Aggregation?
- For Code Reusability.
Simple Example of Aggregation
In this example, we have created the reference of Operation class in the Circle class.
Output:78.5
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.
Understanding meaningful 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.
Address.java
Emp.java
Output:111 varun
gzb UP india
112 arun
gno UP india
No comments:
Post a Comment