As I got into Java seriously, I decided to give several Design Patterns books I own yet another try – I have skimmed through GoF’s master-piece number of times, but being a PHP programmer in PHP4 age, I just had no incentive to study patterns any deeper, as there clearly was no option to apply them. PHP5 is better wrt OO-tion but still looks like a toy.
Overall, I don’t understand the whole idea of implementing simple and easy-to-learn language, get popular, and then redesign the language to include all the goodies from “real languages like C/C++, Java”. But that’s topic for another post, I guess
So, now when I have a little more time to experiment with Java, and as it is as object-oriented as one might dream, I wanted to study patterns in details. I plan to post number of articles later this month, but for now, I wanted to capture one (important if you are planning to use UML and Patterns) simple concept – that’s difference between Aggregation and Composition. As simple as it might seem, there quite a lot of people who don’t understand it.
First of all, both Aggregation and Composition are Associations, and actually share characteristics, so I wouldn’t bother you with “has a”, “is a”, “is part of” cliches, which aren’t as helpful as it’s believed.
Very good definition of Aggregation, goes as following:
Aggregation is a whole/part association where a client object contains one or more server objects, but the client object can be defined with or without the creation of the server object. For instance, a car can contain golf clubs in its back trunk but the car is still a car with or without the golf clubs.
Let me translate. Aggregation is a “whole/part” association, and is used to describe object relationship where object A (client, aggregate, whole) contains object(s) B (server, component, part). Here, important word is “contains” – client literally contains the server object(s), it’s not composed of them.
Actually, that’s the sole difference between Aggregation and Composition, where later is a special case of former.
Before I provide some code examples, here is similar definition of Composition (do compare it with definition of Aggregation):
Composition is a stronger whole/part association where a client object is composed of one or more server objects, such that without the creation of the one or more server objects the client object could not be created. For instance, a car’s composition consists of an engine among other objects. However, the car would not be considered a car if it did not have an engine.
So, Aggregation vs. Composition is really a matter of control over life-cycle of parts within the whole. With Aggregation you can attach parts to whole at any time – for the whole to be initialized presence of parts that the whole might contain is not required. With Composition you have another story: since parts constitute the logical whole with the main object i.e. object is considered to be the sum of all its parts, you have to initialize parts at a time the container object is initialized.
Let’s have a look at examples.
As Aggregation refers to containment, and in Java code might look as following:
import java.util.ArrayList; public class Aggregation { public static void main(String[] args) { Player Kaka = new Player(); Team team = new Team(); team.addPlayer(Kaka); // Kaka is now contained! } } /** * Client, Aggregate, Whole */ class Team { private ArrayList players; public Team() { // player list is empty, we can attach players via addPlayer(), so // that team CONTAINS players, however our team object is not dependant // on players for initialization - we can initialize Team objects even // if we have no intention to put players into them players = new ArrayList(); } public void addPlayer(Player p) { players.add(p); } } /** * Dump Part class */ class Player {}
As you see Team object can exist without any players, and we can attach Player objects at any point after Team’s initialization.
Now, lets turn our attention to Composition example. Here parts should be initialized (generally within constructor of container class) prior to full initialization of container. Do understand that decision on which association is more appropriate depends on our aims, and we can re-write the Team/Player example to express composition if we believe that Team is composed of Players (so no entity could be called Team if it hasn’t got players):
import java.util.ArrayList; public class Composition { public static void main(String[] args) { // player objects life-cycle is totally under container class controll Team team = new Team(); } } /** * Client, Aggregate, Whole */ class Team { private ArrayList players; public Team() { players = new ArrayList(); players.add(new Player()); } } /** * Dump Part class */ class Player {}
As you see the difference is more conceptual. Indeed, when it comes to code, we can use the same constructs (member variables in this case) quite differently. If we have Aggregation in mind, then our container class can hold/contain components, while it doesn’t interested in initialization of those components (and destruction – which is not an issue in Java, due to garbage collection, but should be taken into consideration for, say, C++). If what we mean is Composition, then our container object is literally composed of those parts, and as such initializes them at construction time.
What I want to stress: despite the fact that difference between Aggregation and Composition might be academical at times, their conceptual difference is not that small. And on conceptual level you should understand what you are dealing with. You might be wrong thinking that Aggregation is a better abstraction for a Team/Player concept, but you should understand what aggregation means.
Sorry for such a lengthy explanation of what in essence is quite a simple concept.

[...] Read the rest here: PHP Magazine » Aggregation vs Composition [...]
This is a good definition of the pattern, going much further than sole code. It is when you fully understand the forces that resulting in the creation of a pattern that you can use it wisely.
I’m still learning OOP, but this article has really helped me grasp the difference between Aggregation and Composition, so thank you for clarifying this subject for me!
> If what we mean is Composition, then our container object
> is literally composed of those parts, and as such
> initializes them at construction time.
This is not always true. An object can also ask for his dependencies:
class Team {
public Team(Player p) {
[...]
}
}
and provide what technically is a composition. I prefer this form as it goes along with unit testing.
to PiccoloPrincipe:
Well, when it comes to Java language constructs then the difference btw Aggregation and Composition is not that obvious – what I tried to stress in this post is not the exact code layout, but the meaning of concepts.
Regarding your example – if you are talking about Composition then what you are showing is still the same concept – part is initialized at a time of the whole construction (that’s why you used constructor to accept dependencies). For example:
Team t = new Team(new Player());
If you initialize Player object otherwise, thus it is completely independent from its whole (for example I can destroy passed into constructor Player object), then we have a flaw in design – part could get reset/destroyed/inadvertently changed and the whole would be corrupted as it depends on parts, it is composed of all its parts.
So, difference is more semantic in Java – Composition is more tight association, and as such imposes more requirements on implementations.
Very nice definition of the difference between “Aggregation” and “Composition”. They are frequently mixed concepts and used as they are exchangeable.
There is a little difference in the UML notation of “Aggregation” and “Composition” too.
“Aggregation” is shown empty diamond-shaped arrowhead pointing towards the target or parent class.
|Node|——–>|Node|
class Node
{
private:
vector itsNodes;
};
“Composition” is shown filled diamond-shaped arrowhead pointing towards the target or parent class.
|Car|——–>|Carburetor|
class Car
{
public:
virtual ~Car() {delete itsCarb;}
private:
Carburetor* itsCarb
};
In my previous comment, the example is not shown properly by using text. I’m so sorry.
It is now more clear I think: http://upload.wikimedia.org/wikipedia/en/d/d0/Aggregation-Composition3.png
Nice point Abdullah!
I originally wanted to add UML diagrams to my post, but it was already quite big enough, so I went along with plain-text explanations only.
Your comment would certainly add up to the value of explanation, as a picture is worth a thousand words..
That’s a beautiful explanation and an analogy you have taken to explain.
Keep up the good work.
Cheers,
Raghavan alias Saravanan M.
Very well explained. Thanks for the post
Raji
Wikipedia
http://en.wikipedia.org/wiki/Object_composition#Aggregation sees the difference between Aggregation and Composition, that aggregation does not imply ownership.
Another analogy: If you have a racing team with two cars and ten engines, you can aggregate any of the engines into any car in a 1:1-relationship. When you crash the car, the engine sometimes might be used in the other car. In a composition, if the car gets crashed, the engine is always destroyed as well.
thanks for the nice/clear explaination of aggregation and composition Victor!
Thanks a lot. Very well written explanation.
hi, Its really very very good example. cleared my fundamentals. I also want same good explanation of Interface Vs abstract classes.
As both can work as super type.
except multiple inheritance difference, tell me some real time scenario where only class fits and in other where only interface fits well.
3.where both can be used interchangeably,
I will very thankful to you all. if you guys answer this.
Thanks
Good description but the code samples are both showing composition. If you look the constructor for the agregation code sample it creates an object. This is composition since the object will be gone after the Team class is gone.
ops, did not see the right part. actually it is correct
That was a good explaination using a example .I am clear with the aggregation and composition now!!
Thanks buddy