Aggregation in Java
Aggregation in Java is a special kind of association. It
represents the Has-A relationship between classes. Java
Aggregation allows only one-to-one relationships.
If an object is destroyed, it will not affect the other object,
i.e., both objects can work independently.
Let’s take an example. There is an Employee in a
company who belongs to a particular Department. If the
Employee object gets destroyed still the Department can
work independently.
The end of the Employee object will not affect or destroy
the Department object. The Aggregation is represented as
a line with a diamond..
Aggregation Example :
package aggr;
class Address
{
int streetNum;
String city;
String state;
String country;
Address(int streetNum, String city, String state,
String country)//constructor in Address class
{
this.streetNum=streetNum;
this.city =city;
this.state = state;
this.country = country;
}
}
class Student
{
int rollNum;
String studentName;
Address studentAddr;
//Creating HAS-A relationship with Address
class//student has a address
Student(int rollNum, String studentname,Address
studentAddr)
{ // constructor of StudentClass
this.rollNum=rollNum;
this.studentName=studentname;
this.studentAddr = studentAddr;
}
public static void main(String args[]){
Address ad = new Address(55, "Agra", "UP",
"India");
Student obj = new Student(123, "Raina",ad);
System.out.println(obj.rollNum);
System.out.println(obj.studentName);
System.out.println(obj.studentAddr.streetNum);
System.out.println(obj.studentAddr.city);
System.out.println(obj.studentAddr.state);
System.out.println(obj.studentAddr.country);
}
}