原因 - List list = new ArrayList(); [英] Reason for - List list = new ArrayList();

查看:21
本文介绍了原因 - List list = new ArrayList();的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样的代码我见过很多次了:

I have seen code like this many times:

Listlist = new ArrayList();

为什么人们取ArrayList(和其他类)的父类而不是生成对象的类型?

Why do people take the parent of ArrayList (and other classes) instead of the type of the generated object?

那会降低性能吗?或者为什么有人要这样做?

Does that take less performance? Or why should someone do this?

推荐答案

当有人写这样的代码时,他/她试图遵循基本的 OO 设计原则,即 -

When someone writes code like this, he/she is trying to follow a basic OO design principle which says -

针对接口编程,而不是针对具体实现

Program to an interface, not to a concrete implementation

我在我的一篇博文中解释了这个原则.查看 Class Inheritance VS Interface Inheritance 部分.

总结这篇文章,当你使用父类型的引用来引用子类型的实例时,你会获得很大的灵活性.例如,如果您将来需要更改您的子类型实现,您将能够轻松地做到这一点,而无需更改您的大部分代码.

To summarize the post, when you use a reference of a parent type to refer to an instance of a sub-type, you get a lot of flexibility. For example, if you ever need to change your sub-type implementation in the future, you will be able to do that easily, without changing much of your code.

考虑以下方法 -

public void DoSomeStuff(Super s) {
    s.someMethod();
}

并调用此方法 -

DoSomeStuff(new Sub());

现在,如果您需要更改someMethod 内部的逻辑,您可以通过声明一个新的Super 子类型来轻松实现,例如NewSubType,并更改该实现中的逻辑.通过这种方式,您将永远不必接触使用该方法的其他现有代码.您仍然可以通过以下方式使用 DoSomeStuff 方法 -

now, if you ever need to change the logic inside someMethod, you can easily do it by declaring a new subtype of Super, say NewSubType, and changing the logic inside that implementation. In this way, you will never have to touch other existing code which utilizes that method. You will still be able to use your DoSomeStuff method in the following way -

DoSomeStuff(new NewSubType());

如果您将 DoSomeStuff 的参数声明为 Sub,那么您也必须更改其实现 -

Had you declared the parameter of DoSomeStuff to be of Sub, you would then have to change its implementation too -

DoSomeStuff(NewSubType s) {
    s.someMethod();
}

它也可能链接/冒泡到其他几个地方.

and it may also chain/bubble to several other places.

就您的集合示例而言,这使您可以轻松更改变量指向的列表实现.您可以轻松地使用 LinkedList 代替 ArrayList.

In terms of your collection example, this lets you change the list implementation that a variable is pointing to without much hassle. You can easily use a LinkedList in place of an ArrayList.

这篇关于原因 - List list = new ArrayList();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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