Aggregation in Java

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.

class Student
{
int id;
int rollno;
String name;
Address address; //Address is a class
}

The following is a simple example to understand the concept of aggregation.



In this example, we created the reference to the calculation class in the circle class.

class Calculation
{
int multiply(int n)
{
return 2*n;
}
}

class Circle
{
Calculation cal; //aggregation
double pi=3.14;
double circumference(int radius) {
cal=new Calculation();
int nmultiply=cal.multiply(radius); ///code reusability
return pi*nmultiply;
}

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

Output: 43.96

When aggregation is 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

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

Student.java

public class Student
{
int id;
String name;
Address address;
public Student(String name,int id,Address address)
{
this.address=address;
this.name=name;
this.id=id;
}
void display() {
System.out.println(id+""+name);
System.out.println(address.city+""+address.state+""+address.country+""+address.pin);
}
public static void main(String args[]) {
Address address1=new Address("Jhansi","UP","India",284003);
Address address2=new Address("Lucknow","UP","India",230056);
Student student1=new Student("Rahul",1000,address1);
Student student2=new Student("Shubham",2000,address2);

student1.display();
student2.display();
}
}

Output: 1000Rahul

JhansiUPIndia284003

2000Shubham

LucknowUPIndia23005

Up Next
    Ebook Download
    View all
    Learn
    View all