Search code examples
javaumlinstantiationclass-diagram

UML relationship of class and object it creates inside the creation of another object?


For example, in java:

public class App {

    public void method() {

        Object1 o1 = new Object1(new Object2(parameters));
    }

}

I know App and Object1 have a composition relationship.

But what about App and Object2? Is it a composition as well?


Solution

  • Using a class in a method is not sufficient for an association

    Your class App has no fields of class Object1 or Object2. It just uses Object1 and Object2 in the implementation of a method. This is not sufficient for making an association: there is no conceptual relationship between App and ObjectX; it's just an implementation detail. And since composition is a special kind of association, there is no composition either.

    Using a class means a dependency

    Since your App uses Object1 and Object2, there is a «use» dependency: App needs to know these classes. You could show this dependency with an open headed dashed arrow.

    However, the dependency in your example is only at the level of the method implementation and not at the level of the class itself. You could implement the method otherwise. I'd therefore advise not to show such a volatile dependency in your model. The dependency would be advisable if the class definition itself would use such an object (e.g. if a method would return an ObjectX or use an ObjectX parameter).

    Terminology: Not all compositions are compositions!

    As explained, there is no composition here. Nevertheless, the word is ambiguous:

    • it could mean object compostion. This is just about objects having fields of another class.
    • it could mean UML composition. This is a special kind of association with exclusive ownership