Coupling


Coupling

Coupling in Java plays an important role when we work use Classes and Objects, where coupling plays an important role. It means the extent of knowledge one class has about the other class.

There are two types of coupling:

  • Tight Coupling: It refers to a group of classes which are highly dependent on each other. Here, an object creates another object for its usage. The parent object has all the data about the child object and therefore it is called as tight coupling.
  • Loose Coupling: When objects are independent, it is called as loose coupling. This type of coupling reduces maintenance and efforts. It overcomes the disadvantage of tight coupling.

Tight coupling vs. loose coupling:

  • The tight coupling harms testability. Loose coupling, on the other hand, promotes testability.
  • Tight connection lacks the concept of an interface. However, flexible coupling allows us to adhere to the GOF philosophy of programming interfaces rather than implementations.
  • It's tough to change the codes between two classes when they are tightly coupled. However, swapping other parts of code/modules/objects/components in loose coupling is considerably easier.
  • Tight coupling cannot change. However, loose coupling is exceedingly variable.

Better option out of tight and loose coupling:

Tight coupling is bad in general, but especially when it lowers code flexibility and reusability, makes changes more complex, obstructs testability, and so on. A loosely connected application will aid you when your application has to adapt or grow, thus it's a better choice. Only a few components of the application should be affected when requirements change if you design with loosely connected architecture.

Example No.1:Tight coupling

Com.knowledge2life public class Main { public static void main(String args[]) { A a = new A(); a.display(); } } class A { B b; public A() { b = new B(); } public void display() { System.out.println("Knowledge2life"); b.display(); } } class B { public B(){} public void display() { System.out.println("website"); } }

OUTPUT:

knowledge2life
website

Example No.2:Loose coupling

Com.knowledge2life class Tester { public static void main(String args[]) { Show b = new B(); Show c = new C(); A a = new A(b); a.display(); A a1 = new A(c); a1.display(); } } interface Show { public void display(); } class A { Show s; public A(Show s) { //s is loosely coupled to A this.s = s; } public void display() { System.out.println("Knowledge2life1"); s.display(); } } class B implements Show { public B(){} public void display() { System.out.println("Knowledge2life2"); } } class C implements Show { public C(){} public void display() { System.out.println("Knowledge2life3"); } }

OUTPUT:

knowledge2life1
knowledge2life2
knowledge2life1
knowledge2life3