我一直在阅读一本关于 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/