Home > Software engineering >  Does using an instance of a class inside of another class count as dependency or association?
Does using an instance of a class inside of another class count as dependency or association?

Time:12-15

I’m having a hard time figuring out whether instantiating a class inside of another and then using some of its methods counts as dependency or association within UML class diagrams. For example:

public class Example {
    Thing thing = new Thing();

    public void method() {
            thing.doSomething();
    }
}

Is this association because Example "has a" Thing? Or is this dependency because Example has a method that "uses" Thing to work properly?

CodePudding user response:

In UML, you would represent this with an association between Example and Thing:

  • Purists would suggest the dot notation and put a tiny dot on the Thing end: this tells that Example owns the end of the association. Not all the modelling tools support this notation.
  • Since the instance of Example would always know the instance of Thing but probably not the opposite, you'd want to show this association navigable (open arrow at the end).

The association implies the dependency. So you should not add a redundant dependency to the diagram. A dependency without association would look like:

public class Example {
    Thing thing = new Thing();             // Example is associated to Thing

    public void method(AnotherThing x) {   // Example depends on AnotherThing
            ...;
    }
}
  • Related