What is the difference between association, aggregation and composition?

 picture · May 20, 2009 · Viewed 370k times · Source

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

Answer

Jeff Foster picture Jeff Foster · May 1, 2012

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 { 
    void Baz(Bar bar) {
    } 
};

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; 
    }
}