UML relationships - dashed line vs solid line

NPS picture NPS · Nov 17, 2014 · Viewed 64k times · Source

What is the difference between these 2 relationships?

enter image description here

Edit: Also if you could provide a simple code example illustrating the difference, that would be really helpful!

Answer

Fuhrmanator picture Fuhrmanator · Jun 21, 2015

I'm trying to give simple examples of the two types of lines.

In the first diagram, the solid line shows an association:

PlantUML diagram of a directed association

If the classes were declared in Java, this would be like ClassA storing a reference to ClassB as an attribute (it could be passed in to the constructor, created, etc.). So, you might see something like:

public class ClassA {
    ClassB theClassB = ...
    ...
}

In the second diagram, it shows a dependency:

PlantUML diagram of dependency

A dependency is much weaker than an association. To quote from UML Distilled:

With classes, dependencies exist for various reasons: One class sends a message to another; one class has another as part of its data; one class mentions another as a parameter to an operation. [...] You use dependencies whenever you want to show how changes in one element might alter other elements.

Again, using Java, a couple of examples exist: an argument of type ClassB is passed to a method, or a method declares a local variable of type ClassB:

public class ClassA {
    ...
    public void someMethod(ClassB arg1) {...}
    ...
    public void someOtherMethod() {
        ClassB localReferenceToClassB = ...
    }
    ...
}

Other ways ClassA could depend on ClassB without having an association (not an exhaustive list):

  • ClassB has a static method that ClassA calls
  • ClassA catches exceptions of type ClassB
  • Whenever ClassB is modified, ClassA must also be modified (e.g., some logic is shared)