多态:为什么使用“List list = new ArrayList"?而不是“ArrayList list = new ArrayList"? [英] Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?
问题描述
可能的重复:
为什么应该首选 Java 类的接口?
我应该什么时候使用
List<Object> list = new ArrayList<Object>();
ArrayList
继承自 List
,所以如果 ArrayList
中的某些特性不在 List
中,那么我会失去 ArrayList
的一些功能,对吧?并且编译器在尝试访问这些方法时会注意到错误?
ArrayList
inherits from List
, so if some features in ArrayList
aren't in List
, then I will have lost some of the features of ArrayList
, right? And the compiler will notice an error when trying to access these methods?
推荐答案
这样做的主要原因是将代码与接口的特定实现分离.当您像这样编写代码时:
The main reason you'd do this is to decouple your code from a specific implementation of the interface. When you write your code like this:
List list = new ArrayList();
您的其余代码只知道数据属于 List
类型,这是可取的,因为它允许您轻松地在 List
接口的不同实现之间切换.
the rest of your code only knows that data is of type List
, which is preferable because it allows you to switch between different implementations of the List
interface with ease.
例如,假设您正在编写一个相当大的 3rd 方库,并假设您决定使用 LinkedList
实现库的核心.如果您的库严重依赖访问这些列表中的元素,那么最终您会发现您做出了一个糟糕的设计决定;您会意识到您应该使用 ArrayList
(它提供 O(1) 访问时间)而不是 LinkedList
(它提供 O(n) 访问时间).假设您一直在为接口编程,那么进行这样的更改很容易.您只需将 List
的实例从,
For instance, say you were writing a fairly large 3rd party library, and say that you decided to implement the core of your library with a LinkedList
. If your library relies heavily on accessing elements in these lists, then eventually you'll find that you've made a poor design decision; you'll realize that you should have used an ArrayList
(which gives O(1) access time) instead of a LinkedList
(which gives O(n) access time). Assuming you have been programming to an interface, making such a change is easy. You would simply change the instance of List
from,
List list = new LinkedList();
到
List list = new ArrayList();
并且您知道这会起作用,因为您已经编写了代码来遵循 List
接口提供的契约.
and you know that this will work because you have written your code to follow the contract provided by the List
interface.
另一方面,如果您已经使用 LinkedList list = new LinkedList()
实现了库的核心,则进行这样的更改不会那么容易,因为无法保证其余代码不使用特定于 LinkedList
类的方法.
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 to 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 to make implementation-specific changes later without breaking existing code.
这篇关于多态:为什么使用“List list = new ArrayList"?而不是“ArrayList list = new ArrayList"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!