Object-oriented – Understanding UML composition better

compositionobject-orienteduml

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??

Best Answer

The question whether the relation between ClassA and ClassB is composite does not depend on whether there also instances of ClassB that are not part of any ClassA. In your example, as long as no reference to the inner ClassB-instance (the one held in your instance variable bInstance) can ever escape the containing instance of ClassA (which could happen if you have a public getter for bInstance, for instance), you are perfectly fine modelling this as a composite relationship.

In your UML model, it is the multiplicity of the container end that determines whether or not all ClassB-instances are expected to be part of some ClassA. The multiplicity of the container end can never be other than [0..1] or [1..1] in the first place, of course (otherwise this would violate the principle that an object can at most be part of a single composition); if it is [0..1] you are saying that there can also be ClassB-instances not part of a ClassA; if it is [1..1] then this is not the case.

See also https://bellekens.com/2010/12/20/uml-composition-vs-aggregation-vs-association/ for an illuminating discussion.