Loose Coupling Example Using Interface

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 the way in which B was implemented, then A & B are tightly coupled.

Loose coupling 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.

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 display method which can accept an object of a class which 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 B class.

Now talking about loose coupling. Suppose in 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
—A.java—

—B.java—

—InterfaceClass—

—Main.class—

OUTPUT
loose coupling

Download Project from Github

4 thoughts on “Loose Coupling Example Using Interface

Leave a Reply

Contact Us
close slider
Contact Us

How can we help you with?