为什么我们在实例化它们之前首先将子类型声明为它们的超类型? [英] Why do we first declare subtypes as their supertype before we instantiate them?

查看:136
本文介绍了为什么我们在实例化它们之前首先将子类型声明为它们的超类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读其他人的代码,我见过很多:

Reading other people's code, I've seen a lot of:

List<E> ints = new ArrayList<E>();
Map<K, V> map = new HashMap<K, V>();

我的问题是:以这种方式实例化它们的优点是什么,而不是:

My question is: what is the point/advantage of instantiating them that way as opposed to:

ArrayList<E> ints = new ArrayList<E>();
HashMap<K, V> map = new HashMap<K, V>();

奇怪的是,我从未见过这样的事情:

What also makes it odd is that I've never seen anything like:

CharSequence s = new String("String");

OutputStream out = new PrintStream(OutputStream);



重复(问题的第一部分):

Duplicates (of the first part of the question):

何时/为何使用/定义界面

在java中使用变量定义的接口或类型?

我应该何时在java中使用接口?

为什么创建接口而不是每个类的实现

这两个java变量声明有什么区别?


推荐答案

快速回答?使用接口和超类可以提高代码的可移植性和可维护性,主要是隐藏实现细节。采用以下假设示例:

Quick answer? Using interfaces and superclasses increases the portability and maintainability of your code, principally by hiding implementation detail. Take the following hypothetical example:

class Account {
    private Collection<Transaction> transactions;

    public Account() {
        super();
        transactions = new ArrayList<Transaction>(4);
    }

    public Collection<Transaction> getTransactions() {
        return transactions;
    }
}

我已经宣布了一个账户合同发布到帐户的交易可以作为集合检索。我的代码的调用者不必关心我的方法实际返回什么样的集合,也不应该。如果我需要的话,这可以让我更改内部实现,而不会影响(也就是打破)未知数量的客户端。所以,如果我发现我需要在我的事务中强加某种独特性,我可以将上面显示的实现从ArrayList更改为HashSet,对使用我的类的任何人都没有负面影响。

I've declared a contract for an Account that states that the transactions posted to the account can be retrieved as a Collection. The callers of my code don't have to care what kind of collection my method actually returns, and shouldn't. And that frees me to change up the internal implementation if I need to, without impacting (aka breaking) unknown number of clients. So to wit, if I discover that I need to impose some kind of uniqueness on my transactions, I can change the implementation shown above from an ArrayList to a HashSet, with no negative impact on anyone using my class.

public Account() {
    super();
    transactions = new HashSet<Transaction>(4);
}

至于你的第二个问题,我可以说你使用的是可行性和封装只要它们有意义。在那里没有可怕的CharSequence实现,而String是迄今为止最常用的。所以你不会看到很多开发人员在他们的代码中声明CharSequence变量。

As far as your second question, I can say that you use the principal of portability and encapsulation wherever they make sense. There are not a terrible lot of CharSequence implementations out there, and String is by far the most used common. So you just won't see alot of developers declaring CharSequence variables in their code.

这篇关于为什么我们在实例化它们之前首先将子类型声明为它们的超类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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