Aggregation and Composition in Java


The distinction between aggregation and composition depends on context.


The composition is stronger than Aggregation. In Short, a relationship between two objects is referred as an association, and an association is known as composition when one object owns other while an association is known as aggregation when one object uses another object. In the case of Composition, One object is OWNER of another object, while in the case of aggregation one object is just a USER or another object.

1. Composition is a strong Association whereas Aggregation is a weak Association.
2. Aggregation relation is “has-a” and composition is “part-of” relation.

Take the example of Team in which Player can stand “on its own” so may not be in composition with a Team. Player which is a part of Team can exist without a team and can become part of other team as well. Just like Car example, it is true that a car exhaust can stand "on its own" so may not be in composition with a car - but it depends on the application. If you build an application that actually has to deal with stand alone car exhausts (a car shop management application?), aggregation would be your choice. But if this is a simple racing game and the car exhaust only serves as part of a car - well, composition would be quite fine.

Chess board Same problem. A chess piece doesn't exist without a chess board only in certain applications. In others (like that of a toy manufacturer), a chess piece can surely not be composed into a chess board.
Things get even worse when trying to map composition/aggregation to your favorite programming language. In some languages, the difference can be easier to notice ("by reference" vs. "by value", when things are simple) but in others may not exist at all.
Composition implies that the child objects share a lifespan with the parent. Aggregation doesn't. For example, a chess board is composed of chess squares - the chess squares don't really exist without the board. However, a car is an aggregation of parts - a car exhaust is still a car exhaust if it's not part of a car at the time.enter image description here
class Person {
    private Heart heart;
    private List<Hand> hands;
}

class City {
    private List<Tree> trees;
    private List<Car> cars
}
In composition (Person, Heart, Hand), "sub objects" (Heart, Hand) will be destroyed as soon as Person is destroyed.
In aggregation (City, Tree, Car) "sub objects" (Tree, Car) will NOT be destroyed when City is destroyed.
The bottom line is, composition stresses on mutual existence, and in aggregation, this property is NOT required.

Comments

Popular posts from this blog

Important Java Interview Questions - Part 7

Design Patterns -- part 1

Access Modifiers in java