Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between association, aggregation and composition?

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

I know this question is tagged as C# but the concepts are pretty generic questions like this redirect here. So I am going to provide my point of view here (a bit biased from java point of view where I am more comfortable).

When we think of Object-oriented nature we always think of Objects, class (objects blueprints) and the relationship between them. Objects are related and interact with each other via methods. In other words the object of one class may use services/methods provided by the object of another class. This kind of relationship is termed as association..

Aggregation and Composition are subsets of association meaning they are specific cases of association.

enter image description here

  • In both aggregation and composition object of one class "owns" object of another class.
  • But there is a subtle difference. In Composition the object of class that is owned by the object of it's owning class cannot live on it's own(Also called "death relationship"). It will always live as a part of it's owning object where as in Aggregation the dependent object is standalone and can exist even if the object of owning class is dead.
  • So in composition if owning object is garbage collected the owned object will also be which is not the case in aggregation.

Confused?

Composition Example : Consider the example of a Car and an engine that is very specific to that car (meaning it cannot be used in any other car). This type of relationship between Car and SpecificEngine class is called Composition. An object of the Car class cannot exist without an object of SpecificEngine class and object of SpecificEngine has no significance without Car class. To put in simple words Car class solely "owns" the SpecificEngine class.

Aggregation Example : Now consider class Car and class Wheel. Car needs a Wheel object to function. Meaning the Car object owns the Wheel object but we cannot say the Wheel object has no significance without the Car Object. It can very well be used in a Bike, Truck or different Cars Object.

Summing it up -

To sum it up association is a very generic term used to represent when a class uses the functionalities provided by another class. We say it's composition if one parent class object owns another child class object and that child class object cannot meaningfully exist without the parent class object. If it can then it is called Aggregation.

More details here. I am the author of http://opensourceforgeeks.blogspot.in and have added a link above to the relevant post for more context.


Association is generalized concept of relations. It includes both Composition and Aggregation.

Composition(mixture) is a way to wrap simple objects or data types into a single unit. Compositions are a critical building block of many basic data structures

Aggregation(collection) differs from ordinary composition in that it does not imply ownership. In composition, when the owning object is destroyed, so are the contained objects. In aggregation, this is not necessarily true.

Trick to remember the difference : "has A" -Aggregation and "Own" - cOmpositoin

context Aggregation Composition
Life time objects have their own lifetime and there is no owner controlled by whole or parent that owns it
Scope parent objects and child objects are independent parent object also means the death of its children.
Relationship Has-A Own
Strength weak relationship strong relationship.
Real-life example Car and Driver Car and wheels

Now let observe the following image

relations

enter image description here

Analogy:

Composition: The following picture is image composition i.e. using individual images making one image.
enter image description here

Aggregation : collection of image in single location

enter image description here

For example, A university owns various departments, and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a University can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a Professor could work in more than one department, but a department could not be part of more than one university.


Dependency (references)
It means there is no conceptual link between two objects. e.g. EnrollmentService object references Student & Course objects (as method parameters or return types)

public class EnrollmentService {
    public void enroll(Student s, Course c){}
}

Association (has-a)
It means there is almost always a link between objects (they are associated). Order object has a Customer object

public class Order {
    private Customer customer
}

Aggregation (has-a + whole-part)
Special kind of association where there is whole-part relation between two objects. they might live without each other though.

public class PlayList {
    private List<Song> songs;
}

OR

public class Computer {
    private Monitor monitor;
}

Note: the trickiest part is to distinguish aggregation from normal association. Honestly, I think this is open to different interpretations.

Composition (has-a + whole-part + ownership)
Special kind of aggregation. An Apartment is composed of some Rooms. A Room cannot exist without an Apartment. when an apartment is deleted, all associated rooms are deleted as well.

public class Apartment{
    private Room bedroom;
    public Apartment() {
       bedroom = new Room();
    }
}

From a post by Robert Martin in comp.object:

Association represents the ability of one instance to send a message to another instance. This is typically implemented with a pointer or reference instance variable, although it might also be implemented as a method argument, or the creation of a local variable.

//[Example:]

//|A|----------->|B|

class A
{
  private:
    B* itsB;
};

Aggregation [...] is the typical whole/part relationship. This is exactly the same as an association with the exception that instances cannot have cyclic aggregation relationships (i.e. a part cannot contain its whole).

//[Example:]

//|Node|<>-------->|Node|

class Node
{
  private:
    vector<Node*> itsNodes;
};

The fact that this is aggregation means that the instances of Node cannot form a cycle. Thus, this is a Tree of Nodes not a graph of Nodes.

Composition [...] is exactly like Aggregation except that the lifetime of the 'part' is controlled by the 'whole'. This control may be direct or transitive. That is, the 'whole' may take direct responsibility for creating or destroying the 'part', or it may accept an already created part, and later pass it on to some other whole that assumes responsibility for it.

//[Example:]

//|Car|<#>-------->|Carburetor|

class Car
{
  public:
    virtual ~Car() {delete itsCarb;}
  private:
    Carburetor* itsCarb
};

As others said, an association is a relationship between objects, aggregation and composition are types of association.

From an implementation point of view, an aggregation is obtained by having a class member by reference. For example, if class A aggregates an object of class B, you'll have something like this (in C++):

class A {
    B & element;
  // or B * element;
};

The semantics of aggregation is that when an object A is destroyed, the B object it is storing will still exists. When using composition, you have a stronger relationship, usually by storing the member by value:

class A {
    B element;
};

Here, when an A object is destroyed, the B object it contains will be destroyed too. The easiest way to achieve this is by storing the member by value, but you could also use some smart pointer, or delete the member in the destructor:

class A {
    std::auto_ptr<B> element;
};

class A {
    B * element;

    ~A() {
        delete B;
    }
};

The important point is that in a composition, the container object owns the contained one, whereas in aggregation, it references it.


It's amazing how much confusion exists about the distinction between the three relationship concepts association, aggregation and composition.

Notice that the terms aggregation and composition have been used in the C++ community, probably for some time before they have been defined as special cases of association in UML Class Diagrams.

The main problem is the widespread and ongoing misunderstanding (even among expert software developers) that the concept of composition implies a life-cycle dependency between the whole and its parts such that the parts cannot exist without the whole, ignoring the fact that there are also cases of part-whole-associations with non-shareable parts where the parts can be detached from, and survive the destruction of, the whole.

As far as I can see, this confusion has two roots:

  1. In the C++ community, the term "aggregation" was used in the sense of a class defining an attribute for referencing objects of another independent class (see, e.g., [1]), which is the sense of association in UML Class Diagrams. The term "composition" was used for classes that define component objects for their objects, such that on destruction of the composite object, these component objects are being destroyed as well.

  2. In UML Class Diagrams, both "aggregation" and "composition" have been defined as special cases of associations representing part-whole relationships (which have been discussed in philosophy for a long time). In their definitions, the distinction between an "aggregation" and a "composition" is based on the fact if it allows sharing a part between two or more wholes. They define "compositions" as having non-shareable (exclusive) parts, while "aggregations" may share their parts. In addition they say something like the following: very often, but not in all cases, compositions come with a life-cycle dependency between the whole and its parts such that the parts cannot exist without the whole.

Thus, while UML has put the terms "aggregation" and "composition" in the right context (of part-whole relationships), they have not managed to define them in a clear and unambiguous manner, capturing the intuitions of developers. However, this is not surprising because there are so many different properties (and implementation nuances) these relationships can have, and developers do not agree on how to implement them.

See also my extended answer to the SO question of Apr 2009 listed below.

And the property that was assumed to define "composition" between OOP objects in the C++ community (and this belief is still widely held): the run-time life-cycle dependency between the two related objects (the composite and its component), is not really characteristic for "composition" because we can have such dependencies due to referential integrity also in other types of associations.

For instance, the following code pattern for "composition" was proposed in an SO answer:

final class Car {    
  private final Engine engine;

  Car(EngineSpecs specs) {
    engine = new Engine(specs);
  }

  void move() {
    engine.work();
  }
}

The respondent claimed that it would be characteristic for "composition" that no other class could reference/know the component. However, this is certainly not true for all possible cases of "composition". In particular, in the case of a car's engine, the maker of the car, possibly implemented with the help of another class, may have to reference the engine for being able to contact the car's owner whenever there is an issue with it.

[1] http://www.learncpp.com/cpp-tutorial/103-aggregation/

Appendix - Incomplete list of repeatedly asked questions about composition versus aggregation on StackOverflow

[Apr 2009]
Aggregation versus Composition [closed as primarily opinion-based by]
[Apr 2009]
What is the difference between Composition and Association relationship?
[May 2009]
Difference between association, aggregation and composition
[May 2009]
What is the difference between composition and aggregation? [duplicate]
[Oct 2009]
What is the difference between aggregation, composition and dependency? [marked as duplicate]
[Nov 2010]
Association vs. Aggregation [marked as duplicate]
[Aug 2012]
Implementation difference between Aggregation and Composition in Java
[Feb 2015]
UML - association or aggregation (simple code snippets)