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

JavaObject Oriented ProgrammingProgramming

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

 Live Demo

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
raja
Published on 15-Oct-2019 10:45:13
Advertisements