Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does composition apply to an implemented class when composing an interface?

There is a class A, an IB interface, and a class B that implements an IB interface. Class A has a field of type IB. During program execution, the value of this field becomes an instance of class B. How to draw a class diagram for this situation? Is there a “composition” relationship between A and IB, and is composition a relationship between A and B, or just a dependency?

like image 336
Anthony Minchenko Avatar asked Oct 24 '25 15:10

Anthony Minchenko


1 Answers

It depends on the language and/or the semantics that you want to give to your construct.

In a language with reference based classes like java:

  • the instance of B could always be shared and therefore continue to live after the death of the A object. This is in contradiction with the composition in UML.
  • an aggregation would allow B to be shared. But unfortunately, the aggregation semantics are not well defined in UML, and is therfore ambiguous.
  • a normal association would be correct and unambiguous.

In a language with value based classes like C++:

  • the composition would appropriately represent the joint lifecycle of the objects
  • in your case however, IB would be polymorpic. Polymorphism would require a pointer. If you'd use a unique_ptr<IB> you would express a composition. Other pointers might allow sharing of objects, so the normal association would be a better representation.

But UML is not a programming language. It's a modelling language. So you should express in the model the semantic that you want. If IB objects are not expected to be shared, and should not outlive A, then composition appropriate shows this intent. If not, remain open.

like image 135
Christophe Avatar answered Oct 27 '25 02:10

Christophe