Aggregation vs Composition
Aggregation:
It represents HAS-A relationship. Aggregation means a class have an entity reference. It is used because it provides code reusability. Inheritance is also used for code reusability but you should use inheritance when if the relationship IS-A is continued throughout the lifetime of the objects involved otherwise use aggregation.
e.g.
class CalculationOperation
{
public float square(float a)
{
return a*a;
}
public float cube(float a)
{
return a*a*a;
}
}
public class Calculator
{
CalculationOperation cop; /* Class Calculator have an entity reference of class CalculationOperation */
public Calculator()
{
cop= new CalculationOperation();
}
public void getAns(float a)
{
System.out.println("Square is:"+cop.square(a));
System.out.println("Cube is:"+cop.cube(a));
}
public static void main(String[] arg)
{
Calculator calc=new Calculator ();
calc.getAns(2);
}
}
Output
Square is:4.0
Cube is:8.0

Composition:
Composition: is also a HAS-A relationship in java classes. Java composition is archived by using instance variables that refers to other object.
e.g.
class Company
{
private String firstname;
public void setFirstname(String firstname)
{
this.firstname=firstname;
}
public void getFirstname()
{
System.out.println("Company name is: "+firstname);
}
}
public class CompanyDetails
{
Company cmp;
public CompanyDetails()
{
cmp=new Company();
cmp.setFirstname("Intellipaat");
}
public void getCmpName()
{
cmp.getFirstname();
}
public static void main(String[] arg)
{
CompanyDetails cd=new CompanyDetails();
cd.getCmpName();
}
}
Output
Company name is: Intellipaat
Learn more about Cross-Platform Mobile Technology for Android and iOS using Java in this insightful blog now!