loose coupling and tight coupling
Coupling is the degree to which one class knows about another class. If the only knowledge that class A
has about class B, is what class B has exposed through its interface, then class A and
class B are said to be loosely coupled…that's a good thing. If, on the other hand,
class A relies on parts of class B that are not part of class B's interface, then the
coupling between the classes is tighter…not a good thing. 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.
Tight Coupling
we have two classes first is traveller and the second is a car. Traveller class is calling logic of car class; in this case traveller
class creates an object of car class.
This will mean the car class will depend on the traveller object.
public class Car {
public void move(){
}
}
public class Plane {
public void move(){
}
}
public class Traveller {
Car c = new Car();
public void startJourney() {
c.move();
}
}
Here traveller object is tightly coupled with car object.
If traveler wants to change from car to plane then the whole traveler class has to be changed like the following:
public class Traveller {
Plane p = new Plane();
public void startJourney() {
p.move();
}
}
Loose Coupling
Our main object, traveler in this case will allow an external entity, a so called container to provide the object. So traveler doesn't have to create an own class from the car or plane object it will get it from the container
When a object allow dependency injection mechanism.
The external entity, the container can inject the car or plane object based on a certain logic, a requirement of the traveler.
public interface Vehicle{
public abstract void move();
}
public class Car implements Vehicale {
Public void move(){
}
}
public class Plane implements Vehicale{
Public void move(){
}
}
public class Traveller {
Vehicle v;
public void setV(Vehicle v) {
this.v = v;
}
public void startJourney() {
v.move();
}
}
Here traveler class injects either a car or a plane object. No changes required in traveler class if we would like to change the dependency from car to a plane.
Traveler class took a vehicle reference, so an external object (Container) can inject either car object or plane object, depends on requirement of traveler.