Tightly coupling
concept
package govind;
public
class Topic {
public
void understand()
{
System.out.println("Tight
coupling concept");
}
}
package govind;
public
class Subject {
Topic t=new
Topic();
public void
startReading()
{
t.understand();
}
public static
void main(String[] args) {
Subject s=new
Subject();
s.startReading();
}
}
o/p:----------
Tight coupling concept
Explanation: In the above
program the Subject class is dependents on Topic class. In the above program
Subject class is tightly coupled with Topic class it means if any change in the
Topic class requires Subject class to change. For example, if Topic class
understand() method change to gotit() method then you have to change the
startReading() method will call gotit() method instead of calling understand()
method.
loosely coupling concept
package govind;
public
interface TopicInterface {
public
void understand();
}
package govind;
public
class Topic1 implements TopicInterface {
@Override
public
void understand() {
System.out.println("understand");
}
}
package govind;
public
class Topic2 implements
TopicInterface{
@Override
public
void understand() {
System.out.println("gotit");
}
}
package govind;
public
class Sub {
public
static void
main(String[] args) {
TopicInterface t1=new
Topic1();
TopicInterface t2=new
Topic2();
t1.understand();
t2.understand();
}
}
o/p:-------------
understand
gotit
Explanation : In the above example, Topic1 and Topic2 objects are loosely
coupled. It means TopicInterface is an interface and we can inject any of the
implemented classes at run time and we can provide service to the end user.
Note:-----------
In order to over
come from the problems of tight coupling between objects, spring framework uses
dependency injection mechanism with the help of POJO/POJI model and through
dependency injection its possible to achieve loose coupling.
package govind;
public class Box {
public double volume;
public Box(double length,double width,double height)
{
this.volume=length*width*height;
}}
package govind;
public class Volume {
public static void main(String[] args) {
Box b=new Box(5.0, 5.0, 5.0);
System.out.println(b.volume);
}
}
Explanation:In the above example, there is a strong inter-dependency
between both the classes. If there is any change in Box class then they
reflects in the result of Class Volume.
package
govind;
public
final class
Box1 {
private
double volume;
public
Box1(double length,double width,double height)
{
this.volume=length*width*height;
}
public
double
getVolume()
{
return volume;
}}
package govind;
public
class Volume1 {
public
static void
main(String[] args) {
Box1 b=new
Box1(5.0, 5.0, 5.0);
double d=b.getVolume();
System.out.println(d);
}
}
Explanation : In the above
program, there is no dependency between both the classes. If we change anything
in the Box1 classes then we dont have to change anything in Volume1 class.
No comments:
Post a Comment