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.
1. class Employee{
2. int id;
3. String name;
4. Address address;//Address is a class
5. ...
6. }
In such case, Employee has an entity reference address, so relationship is
Employee HAS-A address.
Why use Aggregation?
o For Code Reusability.
Simple Example of Aggregation
In this example, we have created the reference of Operation class in the
Circle class.
1. class Operation{
2. int square(int n){
3. return n*n;
4. }
5. }
6.
7. class Circle{
8. Operation op;//aggregation
9. double pi=3.14;
10.
11. double area(int radius){
12. op=new Operation();
13. int rsquare=[Link](radius);//code reusability (i.e. delegates the
method call).
14. return pi*rsquare;
15. }
16.
17.
18.
19. public static void main(String args[]){
20. Circle c=new Circle();
21. double result=[Link](5);
22. [Link](result);
23. }
24. }
Test it Now
Output:78.5
When use Aggregation?
o Code reuse is also best achieved by aggregation when there is no is-a
relationship.
o 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.
[Link]
1. public class Address {
2. String city,state,country;
3.
4. public Address(String city, String state, String country) {
5. [Link] = city;
6. [Link] = state;
7. [Link] = country;
8. }
9.
10. }
[Link]
1. public class Emp {
2. int id;
3. String name;
4. Address address;
5.
6. public Emp(int id, String name,Address address) {
7. [Link] = id;
8. [Link] = name;
9. [Link]=address;
10. }
11.
12. void display(){
13. [Link](id+" "+name);
14. [Link]([Link]+" "+[Link]+" "+[Link]
y);
15. }
16.
17. public static void main(String[] args) {
18. Address address1=new Address("gzb","UP","Ethiopia");
19. Address address2=new Address("gno","UP","Ethiopia");
20.
21. Emp e=new Emp(111,"varun",address1);
22. Emp e2=new Emp(112,"arun",address2);
23.
24. [Link]();
25. [Link]();
26.
27. }
28. }
Test it Now
Output:111 varun
gzb UP Ethiopia
112 arun
gno UP Ethiopia