Java HAS-A relationship : aggregation



Consider we are storing the information of the student, then we may create a class like below –

Class Student {
   int roll;
   String sname;
   Address address;
}

In the above class we have entity reference “Address” which stores again its own information like street,city,state,zip. like below –

Class Address {
   String street;
   String state;
   String zip;
   String city;
}

so we can say that Student HAS-A Address Thus if the class has entity reference then entity will represent the HAS-A relationship.

Consider the following example –

Address.java

public class Address {
    String street;
    String city;
    String state;
    String zip;

   public Address(String street, String city, 
		      String state, String zip) {
    this.street = street;
    this.city = city;
    this.state = state;
    this.zip = zip;
   }
}

Student.java

public class Student {
	
   int roll;
   Address address;

   Student(int rollNo,Address addressDetail){
      roll = rollNo;
      address = addressDetail;
   }
	
    void printStudentDetails(Address address1) {
       System.out.println("Roll   : " + roll);
       System.out.println("Street : " + address1.street);
       System.out.println("City   : " + address1.city);
       System.out.println("State  : " + address1.state);
       System.out.println("Zip    : " + address1.zip);
    }	
	
    public static void main(String[] args) {
       Address address1;
       address1 = new Address("1-ST","PN","Mah","41");
       Student s1 = new Student(1,address1);
       s1.printStudentDetails(address1);
    }
}

Output :

Roll   : 1
Street : 1-ST
City   : PN
State  : Mah
Zip    : 41

Explanation : Advantages of Using Aggregation

  1. You can see the above code in which we already have the class “Address” which is used to store the details of address. Thus using aggregation we have reused the existing class.
  2. Inheritance can be achieved only using the IS-A relationship but using this HAS-A we can use existing code more efficiently.