❮ Previous Next ❯

Tight Coupling & Loose Coupling between Java Objects

T This is the core module of Spring framework. It is the key concept of Spring. Without this, we can’t do anything. So dear frnds, go through it seriously.

coupling

Tight Coupling

When the object of a class depends on another object then there exists tight coupling.

If this happen there is the so called tight-coupling between the two classes.

In this case the first class that wants to call the logic from the second class will have to create an object from the second class

Example: 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 Traveller 
{
Car c = new Car();
public void Journey() 
{
c.move();
}
}
public class Car 
{
public void move()
{
System.out.println(“journey by Car”);
}
}

Here Traveller object is tightly coupled with Car object, because any changes raised instead of Car class, it is directly affecting to Traveller class. Hence we can say the relationship exists between Traveller and Car class is tight coupling. That means if traveler wants to change from car to plane then the whole Traveller class has to be changed like the following:

public class Traveller
{
plane p = new Plane();
public void Journey()
{
p.move();
}
}
public class Plane 
{
public void move()
{
System.out.println(“journey by Plane”);
}
}


Loose Coupling

Let’s see the following example:

public class Traveller 
{
Vehicle v;
public void setv(Vehicle v) 
{
this.v = v;
}
public void Journey() 
{
v.move();
}
}
interface Vehicle
{
void move();
}

class Car implements vehicle
{
public void move()
{
System.out.println(“journey by Car”);
}

class Plane implements Vehicle
{
public void move();
{
System.out.println(“journey by Plane”);
}
}

here from the above the relationship exists between Traveller and Car class is loosely coupled, because any changes raised instead of Car class(assume it changes to Plane class), then it is not directly affecting to Traveller class. Hence we can Traveller and Car class relationship is loose coupling, similarly Traveller and Plane class is loose coupling.


❮ Previous Next ❯

Follow Us




  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved