• Tight Coupling: When two classes are tightly coupled, they are dependent on each other. If one class changes, the other class will also change.
  • Loose Coupling: When two classes are loosely coupled, they are not dependent on each other. If one class changes, the other class will not change.

In the example below, GameRunner class has a dependency on GamingConsole. Instead of wiring game object to a specific class such as MarioGame, we can use GamingConsole interface to make it loosely coupled. So that, we don’t need to change our original code. In the future, we can create classes that implements GamingConsole interface (Polymorphism) and use it.

 

public class GameRunner {  
  // public MarioGame game; // Tightly coupled to a specific game, so we need to change this.  
  private final GamingConsole game; // Loosely coupled, it's not a specific game anymore. Games implement GamingConsole interface. Polymorphism.  
  public GameRunner(GamingConsole game) {  
  this.game = game;  
  }  
  
  public void run() {  
  System.out.println("Running game: " + game);  
  game.up();  
  game.down();  
  game.left();  
  game.right();  
  }  
}

Leave a Reply

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