blog 1 img.jpg

5 Steps to Loose Coupling In Java Using Interfaces.

Description

Loose coupling between classes is the desirable state of having classes that are well encapsulated, minimize references to each other. On the other hand, cohesion is all about how a single class is designed. The term cohesion is used to indicate the degree to which a class has a single, well-focused purpose. The more focused a class is the higher its cohesiveness a good thing.

Summary

  • Introduction
  • Loose Coupling
  • Meaning
  • Loose Coupling vs Tight Coupling
  • Loose Coupling Example
  • Output
  • Conclusion

Coupling is the degree to which one class knows about another class. If the only knowledge that class A has about class B is what class B has exposed through its interface, then class A and class B are said to be loosely coupled, which is good.

If, on the other hand, class A relies on parts of class B that are not part of class B’s interface, then the coupling between the classes is tighter, and, that is not good.

In other words, if A knows more than it should about how B was implemented, then A & B are tightly coupled.

Loose Coupling

Meaning

Loose coupling between software components is the desirable state of having classes that are well encapsulated, minimize references to each other.

On the other hand, cohesion is all about how a single class is designed. The term cohesion is used to indicate the degree to which a class has a single, well-focused purpose. The more focused a class is the higher its cohesiveness a good thing.

Loose Coupling vs Tight Coupling

  • Let’s understand it with an example of how loose coupling has an advantage over tight coupling.
  • We have two classes A and B.
  • Class B implements Interface i.e. InterfaceClass.
  • InterfaceClass defines a Contract for B class as InterfaceClass have abstract methods of B class that can be accessed by any other class for example A.
  • In Class A we have a display method that can accept an object of a class that implements InterfaceClass (in our case it is B class). And on that object method of class A is calling display() and getVar() of class B
  • In MainClass we have created an object of Class A and B. And calling display method of A by passing the object of B class i.e. objb. The display method of A will be called with the object of the B class.

Now talking about loose coupling. Suppose in the future you have to change the name of Class B to ABC then you do not have to change its name in the display method of class B, just make the object of new (ABC class) and pass it to the display method in MailClass. You do not have to change anything in Class A.

Leave a comment