看别人的代码,见多了:
List<E> ints = new ArrayList<E>();
Map<K, V> map = new HashMap<K, V>();
我的问题是:以这种方式实例化它们有什么意义/优势:
ArrayList<E> ints = new ArrayList<E>();
HashMap<K, V> map = new HashMap<K, V>();
让我感到奇怪的是,我从未见过这样的事情:
CharSequence s = new String("String");
或
OutputStream out = new PrintStream(OutputStream);
Duplicates (of the first part of the question):
When/why to use/define an interface
Use interface or type for variable definition in java?
When should I use an interface in java?
why are interfaces created instead of their implementations for every class
What's the difference between these two java variable declarations?
最佳答案
快速回答?使用接口(interface)和父类(super class)增加了代码的可移植性和可维护性,主要是通过隐藏实现细节。举个假设的例子:
class Account {
private Collection<Transaction> transactions;
public Account() {
super();
transactions = new ArrayList<Transaction>(4);
}
public Collection<Transaction> getTransactions() {
return transactions;
}
}
我已经为一个帐户声明了一份契约(Contract),该契约(Contract)声明发布到该帐户的交易可以作为一个集合检索。我的代码的调用者不必关心我的方法实际返回的集合类型,也不应该关心。如果需要,这让我可以自由地更改内部实现,而不会影响(又名破坏)未知数量的客户。也就是说,如果我发现我需要对我的事务施加某种唯一性,我可以将上面显示的 实现 从 ArrayList 更改为 HashSet,而不会对使用我的类的任何人产生负面影响.
public Account() {
super();
transactions = new HashSet<Transaction>(4);
}
至于你的第二个问题,我可以说你在任何有意义的地方都使用了可移植性和封装的原则。那里没有太多可怕的 CharSequence 实现,而 String 是迄今为止最常用的。所以你不会看到很多开发人员在他们的代码中声明 CharSequence 变量。
关于java - 为什么我们在实例化它们之前首先将子类型声明为它们的父类(super class)型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8761188/