What is aggregation in Java?

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. public Address(String city, String state, String country) {
  4.     this.city = city;
  5.     this.state = state;
  6.     this.country = country;
  7. }
  8. }

Employee.java

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

Output

111 varun
gzb UP india
112 arun
gno UP india