Computer >> Computer tutorials >  >> Programming >> Java

What is loose coupling how do we achieve it using Java?


Coupling refers to the dependency of one object type on another, if two objects are completely independent of each other and the changes done in one doesn’t affect the other both are said to be loosely coupled.

You can achieve loose coupling in Java using interfaces -

Example

interface Animal {
   void child();
}
class Cat implements Animal {
   public void child() {
      System.out.println("kitten");
   }
}
class Dog implements Animal {
   public void child() {
      System.out.println("puppy");
   }
}
public class LooseCoupling {
   public static void main(String args[]) {
      Animal obj = new Cat();
      obj.child();
   }
}

Output

kitten