Possible Duplicate:
Why should the interface for a Java class be prefered?
我应该什么时候使用?
List<Object> list = new ArrayList<Object>();
ArrayList
继承自List
,所以如果ArrayList
中的某些功能不在List
中,那么我将失go ArrayList
的一些功能,对吗?当试图访问这些方法时,编译器会注意到一个错误吗?
Possible Duplicate:
Why should the interface for a Java class be prefered?
我应该什么时候使用?
List<Object> list = new ArrayList<Object>();
ArrayList
继承自List
,所以如果ArrayList
中的某些功能不在List
中,那么我将失go ArrayList
的一些功能,对吗?当试图访问这些方法时,编译器会注意到一个错误吗?
这样做的主要原因是将代码与接口的特定实现解耦.当您像这样编写代码时:
List list = new ArrayList();
代码的其余部分只知道数据类型为List
,这更可取,因为它允许您轻松地在List
接口的不同实现之间切换.
例如,假设您正在编写一个相当大的第三方库,并说您决定用LinkedList
实现库的核心.如果你的库严重依赖于访问这些列表中的元素,那么最终你会发现你做了一个糟糕的设计决定;你会意识到你应该使用ArrayList
(它给出了O(1)访问时间)而不是LinkedList
(它给出了O(n)访问时间).假设你一直在编程一个接口,做这样的改变很容易.您只需将List
的实例从,
List list = new LinkedList();
到
List list = new ArrayList();
and you know that this will work because you have written your code 到 follow the contract provided by the List
interface.
On the other hand, if you had implemented the core of your library using LinkedList list = new LinkedList()
, making such a change wouldn't be as easy, as there is no guarantee that the rest of your code doesn't make use of methods specific 到 the LinkedList
class.
All in all, the choice is simply a matter of design... but this kind of design is very important (especially when working on large projects), as it will allow you 到 make implementation-specific changes later without breaking existing code.