Aggregation is a relationship between two classes like association, however its a directional association, which means it is strictly a one way association.For example consider two classes Student class and Address class. each student must have an address so the relationship between student and address is a relationship. But if you consider its vice versa then it would not make sense as an Address doesn’t need to have a Student necessarily. Below example shows this theoretical explanation in a sample java program.
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;
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(69, "Gautam Budh road", "Delhi", "India");
StudentClass obj = new StudentClass(619, "Rey Mysterio", abc);
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);
}
}
No comments:
Post a Comment
Thank you for spending your valuable time!