What is coupling in Java?

The degree of dependency between the components is called coupling. There are two types of coupling in java:-

1. Tight coupling: Degree of dependency between components is high that is called tight coupling. In general, Tight coupling means the two classes often change together. In other words, if A knows more than it should about the way in which B was implemented, then A and B are tightly coupled.

When an object creates the object to be used, then it is a tight coupling situation. As the main object creates the object itself, this object can not be changed from outside world easily marked it as tightly coupled objects.

Example:

class Subject 
{
    Topic t = new Topic(); 

    public void startReading()
    {
        t.understand();
    } 
} 

class Topic
{
    public void understand()
    {
        System.out.println("Tight coupling concept");
    }
}

In the above program the Subject class is dependents on Topic class. In the above program Subject class is tightly coupled with Topic class it means if any change in the Topic class requires Subject class to change. For example, if Topic class understand() method change to gotit() method then you have to change the startReading() method will call gotit() method instead of calling understand() method.

2. Loose coupling: Degree of dependency between components is low that is called loose coupling. Loose coupling is the best choice of coding.

When an object gets the object to be used from the outside, then it is a loose coupling situation. As the main object is merely using the object, this object can be changed from the outside world easily marked it as loosely coupled objects.

Example:

public interface Topic 
{
    void understand(); 
} 

class Topic1 implements Topic
{
    public void understand()
    {
        System.out.println("Got it");
    }
} 

class Topic2 implements Topic
{
    public void unserstand()
    {
        System.out.println("understand");
    } 
}

public class Subject
{
    public static void main(String[] args)
    {
        Topic t = new Topic1();
        t.understand();
    }
} 

In the above example, Topic1 and Topic2 objects are loosely coupled. It means Topic is an interface and we can inject any of the implemented classes at run time and we can provide service to the end user.