Aggregation in Java

Introduction 

 
This article explains Aggregation in Java along with well-explained illustrations for a better understanding.

Consider the situation that a student has his name, roll number and id along with an address that consists of city, pin code, state, and so on. In this case the student has an entity reference address; that means the student has an address.

Aggregation represents a "has-a" relationship.

If a class has an entity reference then it is known as aggregation.

Aggregation is useful for code reusability.
  1. class Student  
  2. {  
  3. int id;  
  4. int rollno;  
  5. String name;  
  6. Address address; //Address is a class  
  7. }  
The following is a simple example to understand the concept of aggregation.



In this example, we created a reference to the calculation class in the circle class.
  1. class Calculation   
  2. {  
  3.  int multiply(int n)   
  4.  {  
  5.   return 2 * n;  
  6.  }  
  7. }  
  8.   
  9. class Circle   
  10. {  
  11.  Calculation cal; //aggregation  
  12.  double pi = 3.14;  
  13.  double circumference(int radius)   
  14.  {  
  15.   cal = new Calculation();  
  16.   int nmultiply = cal.multiply(radius); ///code reusability  
  17.   return pi * nmultiply;  
  18.  }  
  19.   
  20.  public static void main(String args[])   
  21.  {  
  22.   Circle c = new Circle();  
  23.   double result = c.circumference(7);  
  24.   System.out.println(result);  
  25.  }  
  26. }  
Output: 43.96

When is aggregation used?


We use aggregation when we need to reuse code and there is no "is-a" relationship.

Inheritance should be used whenever there exists an "is-a" relationship, otherwise, aggregation is the best.

Another example for understanding aggregation.

There are two Java files, both public classes.

Address.java
  1. public class Address  
  2. {  
  3. String city,state,country;  
  4. int pin;  
  5. public Address(String city,String state,String country,int pin)  
  6. {  
  7. this.city=city;  
  8. this.country=country;  
  9. this.state=state;  
  10. this.pin=pin;  
  11. }  
  12. }  
Student.java
  1. public class Student  
  2. {  
  3. int id;  
  4. String name;  
  5. Address address;  
  6. public Student(String name,int id,Address address)  
  7. {  
  8. this.address=address;  
  9. this.name=name;  
  10. this.id=id;  
  11. }  
  12. void display() {  
  13. System.out.println(id+""+name);  
  14. System.out.println(address.city+""+address.state+""+address.country+""+address.pin);  
  15. }  
  16. public static void main(String args[]) {  
  17. Address address1=new Address("Jhansi","UP","India",284003);  
  18. Address address2=new Address("Lucknow","UP","India",230056);  
  19. Student student1=new Student("Rahul",1000,address1);  
  20. Student student2=new Student("Shubham",2000,address2);  
  21.   
  22. student1.display();  
  23. student2.display();  
  24. }  
Output:
1000Rahul
JhansiUPIndia284003
2000Shubham
LucknowUPIndia23005