开发者

interfaces and their use [duplicate]

开发者 https://www.devze.com 2023-02-27 05:42 出处:网络
This question already has answers here: 开发者_开发百科 Closed 11 years ago. Possible Duplicate:
This question already has answers here: 开发者_开发百科 Closed 11 years ago.

Possible Duplicate:

Use of Java [Interfaces / Abstract classes]

What's the benefit of interfaces over normal Java classes. Someone explained to me that an interface is like a contract, but I just don't get it. Why not just stick with classes?


Interfaces are useful for a couple reasons:

1) A class can extend only one other class, but it can implement any number of interfaces. This allows a method of multiple-inheritance while limiting the difficulties caused by multiple-inheritance.

2) They allow you to hide your implementation when you provide an API to your code, thus allowing you the freedom to change your implementation details in any way you wish as long as you don't violate the previously-defined interface.

For very small projects, interfaces may not be useful. For any medium-sized or large project, interfaces definitely help define the boundaries between the components so that the individual components can be tested in isolation from each other. Appropriate use of interfaces can also help you avoid circular dependencies between your JAR files.

When you are coding against a concrete class, it is easy to make use of implementation details that may not remain in future versions of the class. When you code against an interface, you cannot do this.


Read What Is an Interface? from the Java tutorials, it's well explained.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号