MainMenu

Home Java Overview Maven Tutorials

Monday 21 February 2022

Loose Coupling and Tight Coupling in Java with example

Loose Coupling and Tight Coupling in Java with example



Hello Friends,

This article will describe the concept of tight and loose coupling in java.



Coupling :- Degree of dependency of Class A on Class B.
How often do changes in one class force changes in another class.


Tight Coupling :-
Two classes often change together If class A knows more than it should about the way in which class B was implemented, then A and B are tightly coupled.


Loose Coupling :-
Reducing the dependencies of a class that uses the different classes directly.
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.


Example of Tight coupling
class A1
{
A1(int x , int y)
{
System.out.println("sum is " + (x+y));
}
void sam()
{
System.out.println("i am method of class A");
}
}
class B extends A1
{
B(int x, int y)
//have to add this constructor other wise while creating the object , compile time error will appear. {
super(x, y);
}
void sam()
{
System.out.println("i am method of class B");
}
}
public class Coupling
{
public static void main(String args[])
{
B obj = new B(7, 8);
obj.sam();
}
}


Example of loose coupling
interface mycoup
{
void sample();
}
class A1 implements mycoup
{
A1(int x , int y)
{
System.out.println("sum is " + (x+y));
}
@Override
public void sample()
{
System.out.println("i am method of class A");
}
}
class B implements mycoup
{
public void sample()
{
System.out.println("i am method of class B");
}
}
public class Coupling
{
public static void main(String args[])
{
B obj = new B();
obj.sample();
A1 obj1 = new A1(3, 7);
obj1.sample();
}
}

Output:-
i am method of class B
sum is 10
i am method of class A

No comments:

Post a Comment