03/02/2016
What is the difference between Association, Aggregation and Composition?
A) The three concepts are closely related, indeed. Aggregation and Composition are actually types of Association. The difference between Inheritance and Association is that :
- Inheritance is "is-a" relationship whereas,
- Association is "has-a" or "owns" relationship.
So lets discuss these.
Aggregation :
----------------
It is referred to as weak type relationship. Lets consider an example to understand this concept.
Lets say we have two entities Department and University. University and Department have "has-a" relationship. i.e University has alot of departments. Or more precisely, one large entity can be composed of multiple small entities.
Class department{}
Class University{
private Department dept;
public void setDept(Department dept){
this.dept = dept;
}
}
Weak relationship means if one entity destroys then it doesn't mean that other will also gets destroy. In above example, you can see that dept is coming from outside as a parameter. It is not instantiating here in this class. Or you can think of a List in University class which keeps adding dept in that list(Aggregating department). So this kind of relationship is referred to as weak relationship or aggregation.
Composition:
-----------------
It is referred to as strong relationship. i,e if one entity destroy then other will also destroy as well.
Lets consider example,
class Room{}
class Building{
Room room = new Room();
}
you can see here room is initializing here and it is not referencing outside somewhere. It means its lifetime is attached to the Building class. If building objects destroy then Room object is also gets destroyed. This kind of relationship is referred to as Strong relationship or Composition.
More Example :
A Library contains students and books. Relationship between library and student is aggregation. Relationship between library and book is composition. A student can exist without a library and therefore it is aggregation. A book cannot exist without a library and therefore its a composition.
This example is taken from http://javapapers.com/oops/association-aggregation-composition-abstraction-generalization-realization-dependency/
For other example, you can refer to this link : http://www.coderanch.com/t/522414/java/java/Association-Aggregation-Composition