Tight coupling is when a group of classes are highly dependent on one another.
class C {
A a;
C(B b) {
a = b;
}
}
Interface A {
}
class B implements A {
}
In my code I am accepting object of class through reference of class B not by parent interface A.
Is my code loosely or tightly coupled?
Loose coupling is achieved by means of a design that promotes single-responsibility and separation of concerns.
using the reference of parent class or interface make code more flexible to adopt any child class's object but how does it promotes single-responsibility.
Is loose coupling can be achieved by any other manner rather than using parent class reference variable, in any case not specifically in mine code?
This feels homeworky, but here is my answer.
The code is tightly coupled because the constructor for C
depends upon B
instead of the interface A
. If you wanted to decouple C
from B
, you would accept an instance of A
instead of B
.
Loosely Coupled Code
class C {
A a;
C(A a) {
this.a = a;
}
}