Monday, January 17, 2011

What is the difference between aggregation and composition?

Aggregation is an association in which one class belongs to a collection. This is a part of a whole relationship where a part can exist without a whole.

For example a line item is a whole and product is a part. If a line item is deleted then corresponding product need not be deleted. So aggregation has a weaker relationship.

Ex:

Class employee {

private Department dept;

//setter and getter methods
}

dept can exists even if we delete employee class.since dept can be a member of another class.

Composition is an association in which one class belongs to a collection. This is a part of a whole relationship where a part cannot exist without a whole. If a whole is deleted then all parts are deleted.

For example An order is a whole and line items are parts. If an order deleted then all corresponding line items for that order should be deleted. So composition has a stronger relationship.

Ex:

class Employee {

private Department dept = new Department();

}

If employee is deleted, department also deleted.

No comments:

Post a Comment