Difference between Tight Coupling and Loose Coupling in Objects
Posted By Himanshu Kumar | 14-Dec-2017
Tight Coupling and
In java, a class can get its dependencies by using one of the following 4 ways.
(1) A class can directly create its dependency object with the new keyword.
(2) A class can get its dependencies by calling a factory method.
(3) A class can collect its dependency object from external memory like a registry.
(4) Some external person (entity) can inject class to object into class1.
When one object depends on another and if modifications done on dependency object is demanding the modifications in a caller object also then it is said to be tight-coupling
For example, consider the following 2 classes
In the above example, if a method in Car class is changed from
It is a tight-coupling between objects.
In the above example, suppose if Travel class want another class, says Bike then we need to modify the travel class by replacing Car with Bike. This is also tight-coupling.
In order to avoid tight-coupling between objects, we should follow the below principles.
(1) Use POJI-POJO model for creating dependencies.
(2) Apply dependency-injection mechanism.
For example, create an interface Vehicle and define implementation classes like
Car, Bike, and Flight.
The importance of this model is, methods names in multiple classes will be same and a class cannot change method name. In Travel Class, take a reference of type Vehicle interface, so that it can store any implantation class object of that interface.
There is one vehicle object that is present in Travel object class and it will be needed by the container . So there is no need to make any changes in Travel class.
If the container injects the dependencies required for a class then it is called dependencies
For example, every servlet object needs two dependencies request and response. A servlet
container injects the dependencies to the servlet object. So it is also called dependency