1

我在 java 文档和其他编程书籍中看到的创建对象的不同方式感到困惑。例如

假设有一个base class和一个derived class

1-我有一个类型的变量,Base它指的是类型的对象Derived

List<String> list = new ArrayList<String>();

2-我有一个类型的变量,Derived它指的是类型的对象Derived

ArrayList<String> arrList = new ArrayList<String>();

我的问题是在选择 1 和 2 时我应该怎么想?是否可以利用Polymorphism一般的 Base-Derived 场景?

是否有一段better practice时间在我不知道的 1 和 2 之间进行选择,或者只是一个personal decision

编辑:

对不起,List 是一个接口。 另一个问题:如果我使用 Type 参数,我的决定会改变吗?

ArrayList<T> list = new ArrayList<T>();

更新答案:这实际上称为"Programming to the interface". 感谢代码大师。在这个问题的答案之一中用非常简单的术语解释了我正在寻找的东西 - “编程到接口”是什么意思?

4

3 回答 3

4
  1. List is not a base class it is an interface and therefore should be used wherever possible.

    Using the interface that a class implements allows you to work with all classes that implement the interface, not just the specific class.

  2. String is a concrete class so it is much clearer to use it directly.

    Sometimes, however, even though String implements the CharSequence interface it is unnecessary to use CharSequence because it would just be confusing. However, take a look at StringBuilder, it uses CharSequence almost exclusively.

In summary - there is no better there is just appropriate.

于 2013-02-17T23:44:41.110 回答
3

Choosing the base type allows you to at some point in the future change between using an ArrayList to say a LinkedList, without changing the rest of the code. This gives you more flexibility to refactor later on. Likewise, your public methods should return a List instead of the specific type of List implementation for the same reason -- so that you may change your internal implementation to optimize performance without breaking the contract to your callers.

于 2013-02-17T23:45:25.917 回答
1

在 List 是一个类的情况下(只是为了回答你的问题而假设 - “我们应该使用表示子类的父类的对象还是使用派生类类型的对象(actula 类)?”

1)你是对的,它只是为了多态性。

2)主要用于在不同的类方法中传递对象。其他类的方法可能正在接受父类的输入。你必须在那些地方使用铸件。

于 2013-02-19T17:09:30.377 回答