java - 接口(interface)和实例化

标签 java

我一直在阅读一本关于 Java 的书(Sams 在 21 天自学 Java 第 6 版)并且我有一个问题。

书上说,

Interfaces cannot be instantiated: new can only create an instance of a non-abstract class.

然后它继续并在一段左右的后面说您可以将变量声明为接口(interface)类型,例如。

Iterator loop = new Iterator();

这不是在我们使用 new 时实例化接口(interface)吗?

最佳答案

第二个声明是错误的:

Then it goes on and says a paragraph or so later that "You can declare a variable to be of an interface type for eg. Iterator loop = new Iterator();"

您确实可以声明变量Iterator loop;,您可以使用返回Iterator 的方法、实现Iterator 的类的构造函数或使用匿名内部类,但是您不能直接实例化 Iterator

编辑:

我在网上找到了这本书。但是第5个加法。以下是引述:

Remember that almost everywhere that you can use a class, you can use an interface instead. For example, you can declare a variable to be of an interface type: Iterator loop = new Iterator() When a variable is declared to be of an interface type, it simply means that the object is expected to have implemented that interface. In this case, because Iterator contains an object of the type Iterator, the assumption is that you can call all three of the inter- face’s methods on that object: hasNext(), next(), and remove().

太棒了!有第6版的书就有这么愚蠢的错误!难以置信...

关于java - 接口(interface)和实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21241482/

相关文章:

java - 类型嵌套时 TYPE_USE 注释丢失,通用接口(interface)

java - 我在网上找到的一个有趣的谷歌面试算法,需要线性时间

java - Minecraft bukkit 僵尸生成错误

java - javac生成的类文件中的方法顺序

java - 如何不断地从两个不同的列表中找到两个最小值?

java - 具有更改操作栏操作的可标记 ListView

java - 将自定义元数据添加到二进制文件

java - 如何访问 Thymeleaf 模板中的系统属性?

Java:替换窗口左上角的咖啡杯图标

java - DateTimeFormatter 无法将 String 解析为 LocalDateTime