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

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

问题描述

我见过code像很多次:

I've seen code like this many times:

列表<串GT;名单=新的ArrayList<串GT;();

为什么要采取的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?

推荐答案

当有人写code这样的,他/她正试图遵循一个基本的面向对象的设计原则,说 -

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

我在 1我的博客文章的。期待中的类继承VS接口继承部分。

I have explained this principle in one of my blog posts. Look in the Class Inheritance VS Interface Inheritance section.

要总结后,当你使用父类型的引用来引用一个子类的实例,你会得到一个很大的灵活性。例如,如果您需要更改您在未来的子类型的实现,你将能够做到这一点很容易,无需改变太多的code的。

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

和这个方法的调用 -

and a call to this method -

DoSomeStuff(new Sub());

现在,如果您需要更改内部的someMethod 逻辑,你可以很容易地通过声明超级新亚型做,说 NewSubType ,并改变执行内部的逻辑。这样,你永远不会触及其他现有code一种利用方式。你仍然可以使用你的 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 的参数是,你将不得不改变其执行过 -

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.

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

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