What is aggregation?

Aggregation can be defined as the relationship between two classes where the aggregate class contains a reference to the class it owns. Aggregation is best described as a has-a relationship. For example, The aggregate class Employee having various fields such as age, name, and salary also contains an object of Address class having various fields such as Address-Line 1, City, State, and pin-code. In other words, we can say that Employee (class) has an object of Address class. Consider the following example.

Address.java

  1. public class Address {  
  2. String city,state,country;  
  3.   
  4. public Address(String city, String state, String country) {  
  5.     this.city = city;  
  6.     this.state = state;  
  7.     this.country = country;  
  8. }  
  9.   
  10. }  

Employee.java

  1. public class Emp {  
  2. int id;  
  3. String name;  
  4. Address address;  
  5.   
  6. public Emp(int id, String name,Address address) {  
  7.     this.id = id;  
  8.     this.name = name;  
  9.     this.address=address;  
  10. }  
  11.   
  12. void display(){  
  13. System.out.println(id+” “+name);  
  14. System.out.println(address.city+” “+address.state+” “+address.country);  
  15. }  
  16.   
  17. public static void main(String[] args) {  
  18. Address address1=new Address(“gzb”,”UP”,”india”);  
  19. Address address2=new Address(“gno”,”UP”,”india”);  
  20.   
  21. Emp e=new Emp(111,”varun”,address1);  
  22. Emp e2=new Emp(112,”arun”,address2);  
  23.       
  24. e.display();  
  25. e2.display();  
  26.       
  27. }  
  28. }  

Output

111 varun
gzb UP india
112 arun
gno UP india