为什么在Java中使用接口名称声明变量? [英] Why are variables declared with their interface name in Java?

查看:417
本文介绍了为什么在Java中使用接口名称声明变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个真正的初学者问题(我还在学习Java基础知识)。

This is a real beginner question (I'm still learning the Java basics).

我可以(有点)理解为什么方法会返回List< String> ;而不是ArrayList< String>,或者他们接受List参数而不是ArrayList的原因。如果它对方法没有影响(即,如果不需要ArrayList中的特殊方法),这将使该方法更灵活,更容易用于调用者。其他集合类型也是如此,例如Set或Map。

I can (sort of) understand why methods would return a List<String> rather than an ArrayList<String>, or why they would accept a List parameter rather than an ArrayList. If it makes no difference to the method (i.e., if no special methods from ArrayList are required), this would make the method more flexible, and easier to use for callers. The same thing goes for other collection types, like Set or Map.

我不明白:通常的做法是创建这样的局部变量:

What I don't understand: it appears to be common practice to create local variables like this:

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

虽然此表格不太常见:

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

这里有什么优势?

全部我可以看到一个小缺点:必须添加java.util.List的单独import行。从技术上讲,可以使用import java.util。*,但我也不经常看到,可能是因为某些IDE会自动添加import行。

All I can see is a minor disadvantage: a separate "import" line for java.util.List has to be added. Technically, "import java.util.*" could be used, but I don't see that very often either, probably because the "import" lines are added automatically by some IDE.

推荐答案

当您阅读

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

你明白你所关心的只是一个 List< String> ; 并且您不太重视实际实施。此外,您将自己限制为由 List< String> 声明的成员,而不是特定的实现。您不关心数据是否存储在线性数组或某些奇特的数据结构中,只要它看起来像 List< String>

you get the idea that all you care about is being a List<String> and you put less emphasis on the actual implementation. Also, you restrict yourself to members declared by List<String> and not the particular implementation. You don't care if your data is stored in a linear array or some fancy data structure, as long as it looks like a List<String>.

另一方面,阅读第二行可以让您了解代码关心关于变量 ArrayList< String> 。通过写这篇文章,你隐含地(对未来的读者)说你不应该盲目地改变实际的对象类型,因为其余的代码依赖它实际上是 ArrayList< String>

On the other hand, reading the second line gives you the idea that the code cares about the variable being ArrayList<String>. By writing this, you are implicitly saying (to future readers) that you shouldn't blindly change actual object type because the rest of the code relies on the fact that it is really an ArrayList<String>.

这篇关于为什么在Java中使用接口名称声明变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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