Saturday 17 October 2015

What is Aggregation in java with example

Aggregation is a relationship between two class like association. It is represents as Has-A relationship.


For example we take two class which name is company class and employee class.



For Example



Create a class which name is AggregationCompanyClass.java



/**

 *
 * @author pradeep
 */

class AggregationCompanyClass

{
   int JobId;
   String Name;
   String MobNumber;
   AggregationCompanyClass(int jobId, String name, String mobnumber)
   {
       this.JobId=jobId;
       this.Name =name;
       this.MobNumber = mobnumber;
     
   }
}
class EmployeeClass
{
   int EmpId;
   String EmpName;
   AggregationCompanyClass EmpAddr; 
   EmployeeClass(int id, String name, AggregationCompanyClass addr){
       this.EmpId=id;
       this.EmpName=name;
       this.EmpAddr = addr;
   }
   public static void main(String args[]){
       AggregationCompanyClass addrs = new AggregationCompanyClass(9897357, "HCL", "8000909997");
       EmployeeClass empObj = new EmployeeClass(371, "Monty", addrs);
       System.out.println(empObj.EmpId);
       System.out.println(empObj.EmpName);
       System.out.println(empObj.EmpAddr.JobId);
       System.out.println(empObj.EmpAddr.Name);
       System.out.println(empObj.EmpAddr.MobNumber);
   }

}


Result : Output of this program is



run:

371
Monty
9897357
HCL
8000909997

BUILD SUCCESSFUL


Note : Aggregation is use to maintain code re-usability.  


No comments:

Post a Comment