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.

Java相关问答推荐

在这种情况下我应该/可以使用Java抽象工厂(或工厂方法)吗?

如何在多个设备上同时运行Android Studio的项目?

@GetMapping和@GetExchange有什么区别?

如何使用解析器组合子解析Java数组类型签名?

Java取消任务运行Oracle查询通过JDBC—连接中断,因为SQLSTATE(08006),错误代码(17002)IO错误:套接字读取中断

Springdoc Whitelabel Error Page with Spring V3

从技术上讲,OPC UA客户端是否可以通过转发代理将请求通过 tunel 发送到OPC UA服务器?

Jlink选项&-strie-ative-Commands";的作用是什么?

使用REST客户端和对象映射器从字符串反序列化Json

查找剩余的枚举

使用GridBagLayout正确渲染

Java:使用Class.cast()将对象转换为原始数组

Javadoc在方法摘要中省略方法

使用Jolt将字段转换为列表

未找到适用于响应类型[类java.io.InputStream]和内容类型[Text/CSV]的HttpMessageConverter

try 从REST API返回对象列表时出错

寻找Thread.sky()方法的清晰度

HBox内部的左对齐按钮(如果重要的话,在页码内)

在数组中查找素数时出现逻辑错误

获取月份';s在java中非UTC时区的开始时间和结束时间