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

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

问题描述

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

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

我可以(有点)理解为什么方法会返回一个 List而不是 ArrayList,或者为什么他们会接受 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>();

虽然这种形式不太常见:

While this form is less frequent:

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

这里有什么优势?

我能看到的只是一个小缺点:必须为 java.util.List 添加一个单独的导入"行.从技术上讲,可以使用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 而你不太重视实际的实现.此外,您将自己限制为由 List 声明的成员,而不是特定的实现.你不在乎你的数据是存储在线性数组还是一些奇特的数据结构中,只要它看起来像一个 List.

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.通过写这个,你暗示(对未来的读者)你不应该盲目地改变实际的对象类型,因为其余的代码依赖它确实是一个ArrayList<字符串>.

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天全站免登陆