使用 Collection 接口创建 ArrayList 对象的多态性有什么好处?

2022-01-24 00:00:00 polymorphism java

我研究了多态性,了解到它可以像下面这样进行动态方法绑定.

I studied polymorphism and understand that it can do dynamic method binding like below.

假设类 Animal 是抽象类.

Assuming that class Animal is abstract class.

public class AnimalReference
{
  public static void main(String args[])
  Animal ref                 // set up var for an Animal
  Cow aCow = new Cow("Bossy"); // makes specific objects
  Dog aDog = new Dog("Rover");

  // now reference each as an Animal
  ref = aCow; ref.speak();
  ref = aDog; ref.speak();
}

我曾经创建过 ArrayList 的实例,例如:

I used to create instance of ArrayList like:

ArrayList myList = new ArrayList();

但通常我认为人们会写:

But usually I figured that people write:

Collection myList = new ArrayList();

所以我的困惑是声明为 Collection 有什么好处?另外我不知道你可以在myList"前面有Collection"(这是一个接口而不是抽象类).

So my confusion is what is the benefit of declaring as Collection? Also I didn't know you can have "Collection" (which is an interface not abstract class) in front of "myList".

为什么只说是不好的做法:

Why it is not good practice to just say:

ArrayList myList = new ArrayList();

我阅读了 Collection 接口和 ArrayList Java 文档以及在线教程,但仍然不是很清楚..谁能给我一些解释?

I read Collection interface and ArrayList Java documents as well as online tutorials but still not really clear.. Could anyone give me some explanation?

推荐答案

如果您将 myList 声明为 ArrayList,则固定其具体类型.每个使用它的人都将依赖于这个具体的类型,并且很容易(甚至是无意地)调用特定于 ArrayList 的方法.如果稍后您决定将其更改为例如LinkedListCopyOnWriteArrayList,您需要重新编译 - 甚至可能更改 - 客户端代码.接口编程消除了这种风险.

If you declare myList as ArrayList, you fix its concrete type. Everyone using it will depend on this concrete type, and it is easy to (even inadvertently) call methods which are specific to ArrayList. If sometime later you decide to change it to e.g. LinkedList or CopyOnWriteArrayList, you need to recompile - and possibly even change - client code. Programming for interfaces eliminates this risk.

请注意,在 CollectionArrayList 之间,还有另一层抽象:List 接口.通常,列表的使用模式与映射、集合或队列的使用模式非常不同.因此,工作所需的收藏类型通常在早期就已确定,并且不会改变.将您的变量声明为 List 可以明确此决定,并为其客户提供有关此集合遵守的合同的有用信息.Collection OTOH 通常除了迭代它的元素之外并不是很有用.

Note that between Collection and ArrayList, there is another level of abstraction: the List interface. Typically the usage pattern of a list is very different from that of a map, set or queue. So the type of collection you need for a job is usually decided early on, and is not going to change. Declaring your variable as a List makes this decision clear, and gives its clients useful information regarding the contract this collection obeys. Collection OTOH is usually not very useful for more than iterating through its elements.

相关文章