Aggregation in Java: Understanding HAS-A Relationships in Object-Oriented Programming

Discover how aggregation works in Java with this detailed guide. Learn how one class can reference another class to form a HAS-A relationship, such as an Employee class containing an Address object. Improve your understanding of object-oriented programming with practical examples.



Aggregation in Java

Aggregation is when a class has a reference to another class. This represents a HAS-A relationship.

For example, an Employee class might have an Address object:

Syntax

class Employee {  
int id;  
String name;  
Address address; // Address is a class
...
}

Here, Employee HAS-A address.

Why use Aggregation?

For code reusability.

Simple Example of Aggregation

In this example, Circle class uses an Operation class for calculating the area:

Syntax

class Operation {  
int square(int n) {  
return n * n;  
}  
}  

class Circle {  
Operation op; // aggregation  
double pi = 3.14;  

double area(int radius) {  
op = new Operation();  
int rsquare = op.square(radius); // code reusability
return pi * rsquare;  
}  

public static void main(String args[]) {  
Circle c = new Circle();  
double result = c.area(5);  
System.out.println(result);  
}  
}
Output

78.5

When to use Aggregation?

Use aggregation for code reuse when there is no is-a relationship. Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects.

Meaningful Example of Aggregation

Here, Employee has an Address object. The address contains details like city, state, and country:

Syntax

public class Address {  
String city, state, country;  

public Address(String city, String state, String country) {  
this.city = city;  
this.state = state;  
this.country = country;  
}  
}  

public class Emp {  
int id;  
String name;  
Address address;  

public Emp(int id, String name, Address address) {  
this.id = id;  
this.name = name;  
this.address = address;  
}  

void display() {  
System.out.println(id + " " + name);  
System.out.println(address.city + " " + address.state + " " + address.country);  
}  

public static void main(String[] args) {  
Address address1 = new Address("gzb", "UP", "India");  
Address address2 = new Address("gno", "UP", "India");  

Emp e1 = new Emp(111, "varun", address1);  
Emp e2 = new Emp(112, "arun", address2);  

e1.display();  
e2.display();  
}  
}
Output

111 varun
gzb UP India
112 arun
gno UP India