Evolution #15

Support of composition in Java

Added by Arnaud Blouin about 8 years ago. Updated about 8 years ago.

Status:NewStart date:02 November 2011
Priority:MediumDue date:
Assignee:-% Done:


Target version:-


An element contained in a composition cannot be contained into others compositions. The Java code generated from a UML class diagram should support such principle. It can be an option.

q5.png (11.1 KB) Arnaud Blouin, 07 November 2011 11:14


#1 Updated by Christophe Malgouyres about 8 years ago

Sorry, but i don’t understand the principle of this evolution. Could you please explain it a little, maybe with an example?

#2 Updated by Arnaud Blouin about 8 years ago

For example given the following example:


Velo contains a set of Roue instances. The containment is a composition; so given an instance of Roue, called r1, contained in a Velo, called v1. If you add r1 to another instance of Velo, r1 must be removed from v1. This is the difference between composition and association. The problem is that Java does not support composition natively. Developers have to do that manually like that:

`public void addRoue(Roue roue) {

I suggest to add an option to the code generator to generate Java code that considers compositions.

#3 Updated by Christophe Malgouyres about 8 years ago

Thank you for the quick answer, now i understand.

Seems to me this is a very specific use case, with each side of the composition being navigable, which may be considered as breaking encapsulation. In my opinion, the generator shouldn’t assert which behavior to take, even with such a composition. Why should it replace the composition link, instead of throwing an exception, or doing something else ?

By the way, Java designer includes pre/post conditions, adding them on your operations (to enforce the multiplicity) might be a better answer…

#4 Updated by Arnaud Blouin about 8 years ago

The example I gave you is one possible implementation of composition in Java used to explain you the principle of composition. The semantics of UML composition says that elements of a composition must not be shared with others compositions. I agree that doing that in Java for all kinds of composition is not easy, but it will be great if the generated Java code could have the same semantics than its UML model.

Also available in: Atom PDF