user292965 user292965 - 7 months ago 16
Java Question

Dependency and Association in terms of code

I have a question about dependency and association. My understanding on the terms dependency is that it is like a loose kind of relation, I think of the two class being unrelated but i need to use the other class to complete a task. While association is more like a logical connection between two classes. May I check if my understanding is correct? Is dependency a relation that only affects a part of my code while association is creating a instance inside the other class? Thanks!

Answer

My understanding on the terms dependency is that it is like a loose kind of relation, I think of the two class being unrelated but i need to use the other class to complete a task. While association is more like a logical connection between two classes

Yes. And there is one important feature: association is always a dependency too

An example of association (field in class):

class A { ... }
class B {
    private A a;
    public B(A a) { ... }
    ...
}

And this is example of a dependency (usage in some method):

class A { public void doA() { ... } }
class B {
    public void doA(A a) { a.doA(); ... }
    ...
}

PS: it is just an example. Usage as return type in some method also implies a dependency (real world pattern example - AbstractFactory)

Comments