Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

spring - How is loose coupling achieved using interfaces in Java when an implementation class is mandatory and bound to interface contract?

How is loose coupling associated with interfaces when we are bound to create an implementation class regardless? The implementation class is forced to implement all those methods defined in the interface. I don't understand how this allows for lose coupling? I'm new to object oriented programming and software design so if you could shed some light on this topic it would super helpful. An example would totally be icing on the cake.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The key point is that an interface doesn't just allow you to write one class which implements it, it allows you to write several.

When you have code which interacts with a class by using an interface, that code is able to work together with any class which implements said interface, regardless of how it implements it. That allows you to feed different classes to the same code without having to modify it.

Please note that interfaces are not the only way to reach a loose coupling of components. Loose coupling just means that components are able to work together without assuming anything about the internal workings of each other. You do that because the more your components treat each other as black boxes, the easier it becomes to do changes at one component without affecting any others. Interfaces can be one tool to work towards this goal, but neither are they required, nor are they the only tool which is worth mentioning in this regard.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...