Aggregation or Has-A relationship is the concept of having data members of another class by using the class instance (Class or interface will be used as data member) . Like if a class contains an instance of another class as a data member including it's own data members, then it's called aggregation.
The scenario could be, You have a class called Person and it contains properties like id, name age including Address address (instance of another class) . Here, the address is the instance of another class called Address and it contains it's own properties country, city, state or zip_code.
In such case, the relationship between Person and Address class is Has-A relationship. We say, Person has Address.
The same will be applied can be too, like Person have email addresses, Person have Houses, Person have bank accounts, Person have cars etc.
Let's implement the above figure:
# Create Address.java class
For simplicity, make all the members of Address class are public.
Address.java class:
package com.company;
public class Address{
public String city;
public String state;
public String country;
public int zip_code;
//creating constructor
public Address(String city, String state, String country, int zip_code){
this.city = city;
this.state = state;
this.country = county;
this.zip_code = zip_code;
}
//getter and setter methods
}
Now create Person.java class in the same package
Person.java class
package com.company;
public class Person{
public int id;
public String name;
public int age;
//instance of Address class
public Address address;
//constructor
public Person(int id, String name, int age, Address address){
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
//main method (should be in a new file )
public static void main (String[] args) {
//create few address instance
Address a1 = new Address("Houston", "Texas", "USA", 77001);
Address a2 = new Address("Chicago", "Illinois", "USA", 60007);
Address a3 = new Address("San Diego", "California", "USA", 91911);
//create few person objects
Person p1 = new Person(101, "Amelia", 28, a1); //a1 is the instance of Address class
Person p2 = new Person(102, "Anna", 35, a1);
Person p3 = new Person(103, "Bailey", 22, a3);
//let's print the information
//first person
System.out.println("First Person");
System.out.println(p1.id +" "+p1.name +" "+p1.age);
System.out.println("Address: "+p1.address.city +" "+ p1.address.state +" "+p1.address.country +" "+ p1.address.zip_code);
//likewise the above
//you can print the 2nd, 3rd person
//details as well
}
}
Run Person.java class now. You will get the following output in the console.
Output:
First Person
101 Amelia 28
Address: Houston Texas 77001
You can now understand that, how we can achieve aggregation in java. Basically, all the production grade applications use the idea of aggregation. Thus, it helps to maintain large codebase easily and dynamically.