Coupling | Tight Coupling vs Loose Coupling | Examples

Coupling | Tight Coupling vs Loose Coupling | Examples

What is Coupling?
When one object is used by another object it is known as Coupling. In general, it is based on dependency. One object dependency over another object.

There are two types of Coupling,

  • Tight Coupling
  • Loose Coupling

First let us see about tight coupling,

Tight Coupling:

When one object is dependent very much over another object it is known as Tight Coupling. Let us understand with an Example.

For understanding this example, let us create an interface first,

We have a Job Interface with a method display in it.

Now to understand this example, let us create 2 classes. Doctor and Engineer which implements the Job Interface.

Now in main class,

This will give us the output,

So far so good, right?

Now let us consider the scenario, The requirement changes in future. We might have to add another professional for example Scientist. What we do now?

We need to create a class, implement job interface and override display method.

In, we need to give reference to Scientist, add the Scientist variable to Constructor and create a new object and pass Scientist Object and then call display() method in App. java.

Too much of work right?

This is known as tight coupling. One object too much dependent and coupled with another object.

So how can we overcome this, here we are going to use concept of Loose coupling.

By this time, you might have guessed – Reducing the dependencies between object is known as Loose Coupling.

Now for the above same requirement with Doctor and Engineer, let us see how can we write the main class with Loosely Coupling method,

Loose Coupling:

Reducing the dependencies of one object with another object is known as Loose Coupling.

The above main method is re-written again with concept of Loose Coupling.

This code looks simpler when compared to Tight Coupled Code.

Instead of passing Doctor and Engineer objects directly, we have passed Job as reference.

During the run time we are passing the required object to perform the process. In this case, even if the requirement changes in future we do not have to make much changes for the above code.

Even when a new profession is introduced, example : Scientist. Now it is easy for us to make code changes without much change.


Leave a Reply

Your email address will not be published. Required fields are marked *