What is the difference between association, aggregation and composition?
Solution 1
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;
}
}
Solution 2
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.
- 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.
Solution 3
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(The formation of a number of things into a cluster) 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
- "Part-Of": cOmPositoin
- "Is-a": Inheritance
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 | Part-of |
Strength | weak relationship | strong relationship. |
Real-life example | Car and Driver | Car and wheels |
Now let observe the following image
Analogy:
Composition: The following picture is image composition i.e. using individual images making one image.
Aggregation : collection of image in single location
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.
Solution 4
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 Room
s. 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();
}
}
Solution 5
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
};
Admin
Updated on July 14, 2022Comments
-
Admin almost 2 years
What is the difference between association, aggregation, and composition? Please explain in terms of implementation.
-
reinierpost over 12 yearsHow much authority does this definition have? Is it supported by the UML standard authors? I it supported by tools?
-
Ajay almost 10 yearsSeems C#/Java code. If that's the case, both Association and Aggregation code are same. In both cases, 'bar' is just referenced and
Bar
object may live on. -
Saket Kumar almost 10 years@Jeff Foster: I have some doubts. If I instantiate bar object in Baz(Bar bar){bar=new Bar(); } in first case. Will it still be association or will it become composition now?
-
ABCD about 9 years@Ajay: Aggregation keeps the reference of the objects which is not the case with association. Hence the difference of implementation.
-
Ahmad Abdelghany over 8 yearsAssociation is a bit stronger than just usage as a method parameter. I believe your association code snippet corresponds more to a Dependency relation. you might want to check Martin Fowler related article
-
Donbhupi over 8 yearsI was going to ask why you cared to answer an already answered question that was asked more than 5 years ago but then I read your blog entry and it was way more informative than some of the answers here. Upvoted!
-
zish over 8 yearsI agree with @Donbhupi your answer is way more informative and correct than many others
-
André Willik Valenti about 8 years@AhmadAbdelghany is correct. First example is a dependency relation. The third one works for association and aggregation.
-
Everyone over 7 yearsIt's really funny when C# and Java developers claim they use composition when it only exists on primitive types with those languages. If you want to really understand composition you have to use C++ where objects can REALLY be part of other objects.. Not just floating in heap memory and holding pointers to each other and claiming there is composition..
-
Everyone over 7 yearsThis should be the only accepted answer. Composition does not exist in C# and Java except with primitive types... Yet you see developers of those languages "explaining" composition. Composition means an object exists INSIDE another. In Java and C# you cant even do it, everything is on the heap and you just hold pointer to it, it is really aggregation not composition. C++ provides composition..
-
Paulo André Haacke about 7 years@Everyone i arrived at the same conclusion as you, but i'm not so sure of it. For example, say i have one class that is semantically owned by one specific class, however the owned object is garbage collected after its owner has already been removed by the garbage collector, is it considered a composition?
-
Paulo André Haacke about 7 yearsCan we have composition within a c# code using managed memory?
-
RBT almost 7 years
death relationship
- scary name but easy to remember for composition relationship. -
Jankapunkt almost 7 yearsAfter reading so much on this topic, this answer is the most intuitive understandable one. Should be put on wikipedia.
-
Jacco over 6 yearsupvote for the incomplete list of repeatedly asked questions.
-
Amit Kaushik over 6 yearswhat if i expose bar in composition case through getter, I will be leaking a reference to that Bar object created in Foo, will it still be composition?? What i feel is its really a bad idea to make these concepts concrete via such simple code, eg. C++ has destructors which can implement this idea well but in Java we will really have to be responsible for implementing composition.
-
Saurabh Raoot over 6 yearsWhoever has down voted this answer. Can you please explain reason for down voting it ?
-
Sid about 6 yearsBeautifully articulated.
-
Riegardt Steyn almost 6 yearsIt's the Robert C. Martin. That's enough authority for me :-)
-
Alexander Popov almost 6 yearsStrictly speaking, employees of a company cannot exist without a company. It is true, you don't kill the people, but they are no longer employees of that company. So I think a better analogy would be with a Branch and Employees, where even if the branch closes, they might continue to be employees of the company.
-
Kulasangar almost 6 yearsyup, absolutely. Do agree... +1 Thanks @AlexPopov for pointing it out. :)
-
dudu over 5 yearsWhat really confuses me is that, in many cases, it is not the owner hold the thing, but the thing it owns "hold" the owner. For example, the car does not have a Engine * type pointer, but the Engine class has a Car type member to store the car that owns it. I don't quite understand it especially the uml relationship of the classes in this case.
-
Dean P about 5 yearsHow exactly would you implement a generic association if all the other options are ruled out? If A is not composed of B (B's value is in A), A is not an aggregation of B (B's reference is not in A), B is not inherited/realized from A nor is B used as a return, parameter or within function usage of A, you're pretty much left with no relation whatsoever.
-
Oliver about 5 years@DeanP It can just be generic for the time being, and later will be converted to one of the 4 (then it becomes implementable); OR it can be a relationship that doesn't fit the 4 like say you want an association that means "looks like", without a generic association you will be forced to use one of the 4, thus misleading the reader, whereas if you use generic you will likely annotate it or put a note explaining what it is, and most people only read notes if they don't understand the symbol ;)
-
Rolly about 5 yearsGood answer. 1) Question for the composition example: Leng and Hand (composition) Person. if i create a class Animal and Sleep then Sleep (agregation) Person; Sleep (agregation) Animal. Is it correct? 2). Hand composition Person:
class Person() { private hand = new Hand }
. Sleep agregation Personclass Person() { private sleep = new Sleep }
Is valid use the key "new" in Sleep? or should i pass it as reference because is agregation?class Person() { private Sleep _sleep; public addSleep(Sleep sleep) { this._sleep = sleep} }
-
Rolly about 5 yearsIn case of agregation. Should i use
class Club(){ _member = new Member }
or pass it as referenceclass Club(){ addMember(Member member) { this._member = member } }
-
www.admiraalit.nl almost 5 yearsWith regard to aggregation, you say "Child objects belong to a single parent". This is not correct. It is valid UML to have shared aggregation, i.e. a child belongs to multiple parents. You acknowledge this in your example about Department as an aggregation of Professors, because you say that a Professor can work for more than one Department.
-
Fouad Boukredine about 4 yearsYup, the only tricky part in determining object relationships is to distinguish between Association and Aggregation. Everything else is clear. +1 from me
-
tjbtech about 4 years@Everyone, unless I'm misunderstanding your point (don't follow how "primitive types" come into this), that sounds like a distinction without a difference. Whether an object is properly within another, or it lives in a random place on the heap, or you don't have to care because garbage collection, it is all conceptually identical in the context of relationships. If we're talking object design here, composition is composition.
-
Everyone about 4 years@tjbtech it isn't conceptually identical, it's very different. What you mentioned has a name, it's aggregation where one object holds a reference to another. Aggregation and composition are conceptually different. In C++, a composed object is one that cannot outlive its composer. In Java and C#, you can destroy the "composer" and the "composed" can still live if something else holds its reference.
-
tjbtech about 4 years@Everyone, design patterns may be implemented somewhat differently depending on language, of course, but their utility as "design patterns" are necessarily derived from remaining substantially implementation-agnostic. Composition always and by definition implies lifetime management by or via the container. The C#/Java scenario you describe could either just be aggregation, where someone else owns the "composed" object, or else it's a faulty implementation due to breaking encapsulation, which is every bit as possible in C++ (exposing a pointer to the owned object, for example).
-
Everyone about 4 years@tjbtech the main difference in C++ and C#/Java in this regard is that when a reference to the composed object is shared in C++, it will invalidate after the composer is destroyed. In C# and Java, GC decides when things die or when they don't. You do not have such control. So if a reference to the composed is held anywhere, it will outlive its composer upon the latter's destruction. Whether or not it breaks encapsulation is a different topic. The bottom line is: you cannot ensure composed's destruction in C#/Java with its composer. Therefore, it can't be composition, but instead aggregation.
-
aderchox about 4 years@www.admiraalit.nl AFAIK shared aggregation does not mean "a child belongs to multiple parents", it's just the other way round, multiple children belong to the same parents. And it's a non-composite aggregation because even if the parents die, the children may survive longer.
-
tjbtech about 4 years@Everyone, again, if anyone is holding a reference to a purportedly owned object, it isn't really owned and, consequently, was never an example of composition to begin with. No point repeating myself beyond that, so agree to disagree, I guess...
-
Everyone about 4 years@tjbtech we can agree to disagree. I don't think C#/Java can have proper composition as the one C++ offers. That's what I said from the get-go.
-
Amirhosein Al almost 4 yearsIs the relationship between an Album and its Tracks a composition? Or an aggregation? How about a Band and its members?
-
Ahmed Alhallag over 3 yearsMustn't aggregation & association be the same from the implementation POV, since the only difference is logically ? I think the aggregation AND association CAN have collection-like containers as references, since this is something that usually is decided by multiplicity, not really related to the relationship type.
-
Ahmed Alhallag over 3 yearsafter a good while of looking around, I think this is the most and only accurate answer to this subject
-
Ahmad Abdelghany over 3 years@AhmedAlhallag True, they are both implemented the same way i.e. "has-a". I never meant to say that aggregation always uses collections. I will try to come up with another example that isn't using collections to avoid confusion. Thanks.
-
Ahmed Alhallag over 3 years@AhmadAbdelghany Thank you for clarification and for your efforts nonetheless.
-
Maggyero over 3 years@aderchox No, shared aggregation means the child (part) is shared by multiple parents (whole), so www.admiraalit.nl is right: this answer is incorrect.
-
Christophe over 3 yearsSorry but the example for the association is not an association, but a simple usage dependency. An association implies the existence of a semantic relationship i.e. links associating concrete instances.
-
Christophe over 3 yearsInteresting. But what you call a weak association is not called an association in UML but a “usage dependency”.
-
Christophe over 3 yearsInteresting. But I’m confused about your notion of unidirectional vs bidirectional. For example, when dealing with an order, the association with the customer is needed to find the name to print on the label, and conversely, when dealing with a customer one need to know about the orders. Isn’t it the same relation that is used in two directions?
-
berimbolo about 3 yearsAssociation can be one way in a UML diagram though so I cannot understand the difference between your example of association and aggregation, they both look to be association. An address isn't part of a Student and I thought aggregation also defined a whole-part relationship, at least according to Bennetts book.
-
qwerty_so over 2 yearsWhat Christophe said. Further the Aggregation is wrong since UML 2.5 which defines that there is no defined semantics and needs to be defined in the modeling domain.
-
Banik over 2 yearsThe Association example can cause many confusions! I hope that CS students are wise enough to check this comment section too. It's very misleading.
-
John about 2 years@Jeff Foster For the first example, the
Foo
is responsible for lifetime ofBar
. So why it not composition?