Alex Rivera | Logout

What is the difference between association, aggregation and composition?

Asked 2009-05-20T02:47:49.813
595

What is the difference between association, aggregation, and composition? Please explain in terms of implementation.

Edit
Report

1 Answer

641

For two objects, Foo and Bar the relationships can be defined

Association - I have a relationship with an object. Foo uses Bar

public class Foo {         
    private Bar bar;
};

NB: See Fowler's definition - the key is that Bar is semantically related to Foo rather than just a dependency (like an int or string).

Composition - I own an object and I am responsible for its lifetime. When Foo dies, so does Bar

public class Foo {
    private Bar bar = new Bar(); 
}

Aggregation - I have an object which I've borrowed from someone else. When Foo dies, Bar may live on.

public class Foo { 
    private Bar bar; 
    Foo(Bar bar) { 
       this.bar = bar; 
    }
}
answered 2012-05-01T07:20:07.167

Your Answer