使用Collection接口创建ArrayList对象的多态性有什么好处? [英] What is the benefit of polymorphism using Collection interface to create ArrayList object?

查看:699
本文介绍了使用Collection接口创建ArrayList对象的多态性有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我研究了多态,并了解它可以像下面那样进行动态方法绑定。

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();

所以我的困惑是宣称收藏的好处是什么?另外我不知道你可以在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 as ArrayList ,修复其具体类型。使用它的每个人都将依赖于这种具体类型,并且很容易(甚至是无意中)调用特定于 ArrayList 的方法。如果以后某个时候您决定将其更改为例如 LinkedList CopyOnWriteArrayList ,您需要重新编译 - 甚至可能更改 - 客户端代码。接口编程消除了这种风险。

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.

注意在 Collection ArrayList ,还有另一个抽象层次: 列表 界面。通常,列表的使用模式与地图,集合或队列的使用模式非常不同。因此,工作所需的收集类型通常很早就会确定,并且不会改变。将您的变量声明为列表可以明确这一决定,并为其客户提供有关此集合服从的合同的有用信息。 集合 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.

这篇关于使用Collection接口创建ArrayList对象的多态性有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆