Mock tests, Interview questions, Tutorials and Tech news
 
 
Home > Programming / tutorials > Difference between Aggregation and Composition

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.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Mixx
  • Google Bookmarks
  • IndianPad
  • Reddit
Categories: Programming / tutorials Tags: , , ,
  1. venky
    January 18th, 2012 at 05:39 | #1

    Super like !. Nice examples to diff agg and comp..

  2. george
    July 3rd, 2011 at 09:44 | #2

    thanks dude!….that’s great!…..

  3. November 13th, 2010 at 01:44 | #3

    sir thank you very much!

  4. November 12th, 2010 at 15:55 | #4

    Thanks for pointing out the mistake. Post updated.

  5. xarlie
    November 12th, 2010 at 15:03 | #5

    Whoa!, dunno if i missed something but this bits are confusing to me:

    1. Code example for aggregation:

    // WebServer is composed of a…

    2. Code example for composition

    // WebServer is an aggregate….

  6. xarlie
    November 12th, 2010 at 15:00 | #6

    Wow, dunno if i missed something, but this is confusing me:

    Code example for aggregation:

    // WebServer is composed of a…

    and

  7. Glenn
    March 12th, 2010 at 09:58 | #7

    very specific post. great!!

  8. August 27th, 2009 at 21:05 | #8

    Thank you very much!

  1. November 15th, 2010 at 07:06 | #1
Get Adobe Flash playerPlugin by wpburn.com wordpress themes