The difference between Composition and Aggregation in UML (and sometimes in programming too) is that with Composition, the lifetime of the objects composing the composite (e.g. an engine and a steering wheel in a car) is dependent on the composite object. While with Aggregation, the lifetime of the objects making up the composite is independent of the composite.
However I'm not sure about something related to composition in UML.
Say ClassA is composed of an object of ClassB:
class ClassA{
ClassB bInstance;
public ClassA(){
bInstance = new ClassB();
}
}
This is an example of composition, because bInstance
is dependent on the lifetime of it's enclosing object.
However, regarding UML notation - I'm not sure if I would notate the relationship between ClassA and ClassB with a filled diamond (composition) or a white diamond (aggregation).
This is because while the lifetime of some ClassB
instances is dependent of ClassA
instances - there could be ClassB
instances anywhere else in the program - not only within ClassA
instances.
The question is: if some ClassB objects are composed with ClassA objects (and thus are dependent on the lifetime of the ClassA objects), but some are not - would the relationship between the two classes in UML be an aggregation or a composition relationship??