ls loose coupling can be achieved by any other manner rather than using parent class reference variable, in general not specifically in mine code?

314 views Asked by At

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.

  1. Is my code loosely or tightly coupled?

    Loose coupling is achieved by means of a design that promotes single-responsibility and separation of concerns.

  2. 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.

  3. 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?

1

There are 1 answers

4
Dan Grahn On BEST ANSWER

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;
    }
}