Tuesday, January 7, 2014

Understanding Association, Aggregation and Composition


Let’s understand association, aggregation and composition used in OOPs concepts.

Association

Association describes *is a relationship between two classes. Association *Uses another object to perform some action on its behalf. For Example:

Manager class *Uses ReportManager class to perform some action on its behalf.

       public class Manager
       {
              public Manager()
              {
                     var report = new ReportManager();
                     report.Initalize();
              }
       }

It is a directional association between Manager and ReportManager.

Aggregation and Composition

Explanation of aggregation and composition cannot be understood separately, explanation of these concepts should go hand in hand.
Aggregation is a special type of an association. Aggregation explains *has a relationship between the two classes. In this object of one class is contained in the other class. If second instance is part of the first instance of a class then it is mentioned as Aggregation between the two classed. For example:
public class Employee
       {
              private Insurance employeeInsurance = new Insurance();

       }

Employee class contains Insurance class to get the employee insurance.
 Insurance class aggregate Employee class or in other words Employee contains Insurance.

One thing to note here is that both employee and Insurance class are independent of each other. There can be an employee in an organisation that does not have insurance.

Take another example where Heart does not exist without Body. The life time of heart depends on Body. If Body is destroyed Heart will also get destroyed. Here we say that Body is composed of Heart. This explains the concept of Composition.
Please provide your feedback for this topic.

2 comments: