What is Java Aggregation?

Before looking into Java Aggregation, let’s have a look at entity reference and the HAS-A relationship.

Entity Reference

An entity reference is a reference to an entity. Entities are used to store data such as a node, user, etc.

HAS-A Relationship

The HAS-A Relationship can be simply explained as instance variables that are used as references to other objects.

Java Aggregation

A class having an entity reference with another class that represents a HAS-A relationship.

Syntax

class teacher 
{
   int subject_code; 
   String subject_name;
   Address address; //its address is a class
   // statements
}

As we can observe above, the syntax has a class called teacher that has an entity reference of address; so, the relationship is teacher HAS-A address.

Uses of aggregation in Java programming

  • code reusability when there is no relationship
  • it’s the best alternative to Inheritance to maintain the lifetime of objects that are involved in the program.
class Address // address class
{
String village,district,state; // information regarding village, district and state
public Address(String village, String district, String state)
{
this.village = village;
this.district = district;
this.state = state;
}
}
public class Emp // Emp class
{
int id;
String name;
Address address;
public Emp(int id, String name,Address address) // constructor holiding values like village, district and state
{
this.id = id;
this.name = name;
this.address=address;
}
void display() // method which displays information of the Employee like details and their address
{
System.out.println(id+" "+name);
System.out.println(address.village+" "+address.district+" "+address.state);
}
public static void main(String[] args) {
Address address1=new Address("Rudraram","Sangareddy","Telangana"); // creating objects of Address class
Address address2=new Address("Gudur","Krishna","Andhra Pradesh");
Emp e=new Emp(1,"Teja",address1); // creating objects of Emp class
Emp e2=new Emp(2,"Siva",address2);
e.display(); // calling display() method
e2.display(); // calling display() method for second time
}
}

Explanation

In the above example, we consider two classes, Address and Employee. The Employee class is related to the Address class by its reference since the this keyword is used to refer to the current class instance variable.

The Address class has some information regarding details of the village, city, and state. In such a case the relation is Employee HAS-A address.

Free Resources