What is the difference between association, aggregation and composition?

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

20 s
20

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

Leave a Comment