OOPs concepts – What is Aggregation in java?



Aggregation is a special form of association. It is a relationship between two classes like association, however its a directional association, which means it is strictly a one way association. It represents a HAS-A relationship.


(If you are doubted with HAS-A and IS-A click here)


Aggregation Example in Java


For example consider two classes Student class and Address class. Every student has an address so the relationship between student and address is a Has-A relationship. But if you consider its vice versa then it would not make any sense as an Address doesn’t need to have a Student necessarily. Lets write this example in a java program.

Student Has-A Address




class Address
{
int streetNum;
String city;
String state;
String country;
Address(int street, String c, String st, String coun)
{
this.streetNum=street;
this.city =c;
this.state = st;
this.country = coun;
}
}
class studentclass
{
int rollNum;
String studentName;
//Creating HAS-A relationship with Address class
Address studentAddr;
studentclass(int roll, String name, Address addr){
this.rollNum=roll;
this.studentName=name;
this.studentAddr = addr;
}
public static void main(String args[]){
Address ad = new Address(55, "Gobi", "TamilNadu", "India");
studentclass obj = new studentclass(130, "Santhoshi", 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);
}
}
output:

C:\Users\PRIYA\Desktop\java>javac studentclass.java

C:\Users\PRIYA\Desktop\java>java studentclass

130
Santhoshi
55
Gobi
TamilNadu
India

The above example shows the Aggregation between Student and Address classes. You can see that in Student class I have declared a property of type Address to obtain student address. Its a typical example of Aggregation in Java.


Comments

POPULAR POSTS

POPULAR POSTS