接口和实例化 [英] Interfaces and instantiation

查看:106
本文介绍了接口和实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been reading a book on Java (Sams Teach Yourself Java in 21 Days 6th edition) and I have a question.

书说,


接口无法实例化 new 只能创建一个非抽象类的实例。

然后它继续说稍后的段落,您可以将变量声明为接口类型,例如。

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();

这不是实例化界面,因为我们正在使用 new

Isn't that instantiating the interface as we are using new?

推荐答案

第二个声明是错误的:


然后它会继续并且稍后会说你可以将变量声明为接口类型,例如。 Iterator loop = new Iterator();

你的确可以声明变量 Iterator循环; ,您可以使用返回 Iterator 的方法初始化它,实现 Iterator 或使用匿名内部类的类的构造函数,但是你无法直接实例化 Iterator

You indeed can declare variable Iterator loop;, you can initialize it using method that returns Iterator, constructor of class that implements Iterator or using anonymous inner class, however you cannot instatiate Iterator directly.

编辑:

我在网上找到了这本书。但第五个问题。以下是引号:

I found this book online. But the 5th adition. Here are the quotes:


请记住,几乎在任何可以使用类的地方,您都可以使用界面。例如,您可以将变量声明为接口类型:
Iterator loop = new Iterator()当一个变量被声明为接口类型时,它只是意味着该对象应该已经实现了接口。在这种情况下,因为Iterator包含Iterator类型的对象,所以假设您可以在该对象上调用所有三个接口的方法:hasNext(),next()和remove()。

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版的书包含如此愚蠢的错误!令人难以置信......

Fantastic! The book that has 6th edition contains so stupid mistake! Unbelievable...

这篇关于接口和实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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