I've had a hard time understanding the difference between composition and aggregation in UML. Can someone please offer me a good compare and contrast between them? I'd also love to learn to recognize the difference between them in code and/or to see a short software/code example.
Edit: Part of the reason why I ask is because of a reverse documentation activity that we're doing at work. We have written the code, but we need to go back and create class diagrams for the code. We'd just like to capture the associations properly.
1. Association between two objects that illustrate the “has-a” relationship is called Aggregation. A composition defines a part-of a relationship, and both the entities are connected to each other. 2.
The composition is stronger than Aggregation. In Short, a relationship between two objects is referred to as an association, and an association is known as composition when one object owns another while an association is known as aggregation when one object uses another object.
Aggregation implies a relationship where the child can exist independently of the parent. Example: Class (parent) and Student (child). Delete the Class and the Students still exist. Composition implies a relationship where the child cannot exist independent of the parent.
In an aggregation relationship, the associated objects exist independently within the scope of the system. In a composition relationship, the associated objects cannot exist independently within the scope of the system. In this, objects are linked together. In this, the linked objects are independent of each other.
As a rule of thumb:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With