Difference between Aggregation and Composition
When studying UML , one of the most important questions which comes to mid of a programmer is , What is the difference between Aggregation and Composition ?
Composition and Aggregation are types of associations. They are very closely related and in terms of programming there does not appear much difference. I will try to explain the difference between these two by java code examples
Aggregation: the object exists outside the other, is created outside, so it is passed as an argument (for example) to the construtor. Ex: People – car. The car is create in a different context and than becomes a person property.
Composition: the object only exists, or only makes sense inside the other, as a part of the other. Ex: People – heart. You don’t create a heart and than passes it to a person.
Code example for aggregation:
// WebServer is aggregated of a HttpListener and a RequestProcessor
public class WebServer {
private HttpListener listener;
private RequestProcessor processor;
public WebServer(HttpListener listener, RequestProcessor processor) {
this.listener = listener;
this.processor = processor;
}
}
Code example for composition
// WebServer is an composition of HttpListener and RequestProcessor and controls their lifecycle
public class WebServer {
private HttpListener listener;
private RequestProcessor processor;
public WebServer() {
this.listener = new HttpListener(80);
this.processor = new RequestProcessor(“/www/root”);
}
}
In composition, whole has responsibility of preventing garbage collection of part.

