Before looking into Java Aggregation, let’s have a look at entity reference and the HAS-A
relationship.
An entity reference is a reference to an entity. Entities are used to store data such as a node, user, etc.
HAS-A
RelationshipThe HAS-A
Relationship can be simply explained as instance variables that are used as references to other objects.
A class having an entity reference with another class that represents a HAS-A
relationship.
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.
class Address // address class{String village,district,state; // information regarding village, district and statepublic 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 classAddress address2=new Address("Gudur","Krishna","Andhra Pradesh");Emp e=new Emp(1,"Teja",address1); // creating objects of Emp classEmp e2=new Emp(2,"Siva",address2);e.display(); // calling display() methode2.display(); // calling display() method for second time}}
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
.