What is the difference between these 2 relationships?
Edit: Also if you could provide a simple code example illustrating the difference, that would be really helpful!
I'm trying to give simple examples of the two types of lines.
In the first diagram, the solid line shows an 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:
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
callsClassA
catches exceptions of type ClassB
ClassB
is modified, ClassA
must also be modified (e.g., some logic is shared)