Association vs aggregation and vs composition



Association:-  Association is relationship where both container object and contained class has it own life cycle and no one is owner is here.

Example :-
Consider student is taught by multiple teachers where Student is container object containing list of teachers. So Teacher is contained object .

What life cycle means here
 Even student is deleted, teacher will continue to exist.

What owner means here
Same teacher can be associated more more student. So student is not owner of that teacher.

What association means to developer
It tells clearly to developer when student is deleted , teacher can stay in memory(or DB) if required . May be it can be associated with further students

Aggregation:-  Aggregation is relationship where both container object and contained object has it own life cycle and but container object is the owner of contained object . It is represented by has a relationship.

Example :-
Consider department has multiple teachers.

What life cycle means here
 Even departments is deleted, teacher will continue to exist

What owner means here
Same teacher can be associated any other department or any other university at one point of time. So department is the owner of that teacher. Yes, if relationship b/w department and that teacher ends then same teacher can't be associated with other department

What association means to developer
It tells clearly to developer when department is deleted , teacher can stay in memory(or DB) if required . so far same as aggregation. Here comes the difference from aggregation. It also tells the developer that at one point of time contained object can have relationship with only one container object


Composition:-  Composition is relationship where life cycle  of contained object is dependent on life cycle of container object . It is stronger form of aggregation  When I say stronger form of aggregation , I mean container object is strong owner of contained object where contained object is bind with life cycle of container object. Also contained object can not linked with any other object. It is also represented by has a relationship.

Example :-
Consider House has number .of rooms

What life cycle means here
 House is deleted, rooms also needs to be deleted.

What strong owner means here
 Contained object is completely binded with life cycle of container object. Also contained object can not linked with any other object

What association means to developer
It tells clearly to developer when house is deleted , room also needs to be deleted from  memory(or DB) if required . 

Comments

Popular posts from this blog

How to solve javax.net.ssl.SSLHandshakeException ?

When to use Java 8 Optional instead of traditional null pointer check ?

What is REST actually?