当定义“Set set = new HashSet()”时,set是接口还是类Set的实例?
在Java中,“Set”和“List”是从“Collection”接口派生的接口。 如果我们使用代码:
import java.util.*;
public class SetExample{
public stactic void main(String[] args){
Set set = new HashSet();
//do something .....
}
}
“Collection”API 中是否有一个类“Set”,我们正在为其创建一个对象(“set”)?或者我们正在实例化一个接口“Set”?
我真的很困惑......:O
In Java, 'Set' and 'List' are interfaces derived from 'Collection' interface.
If we use the code:
import java.util.*;
public class SetExample{
public stactic void main(String[] args){
Set set = new HashSet();
//do something .....
}
}
Is there a class 'Set' in "Collection" API that we are creating an object ('set') of? or we are instantiating a interface 'Set'?
Am really confused.......:O
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 API 中,你会得到一堆隐藏实现的接口。例如 Set 允许您
隐藏任何实现,HashSet 就是其中之一。
In API you get a bunch of interfaces that hides the implementation. e.g. Set allows you
to hide any implementation, for which HashSet is one of.
java.util.Set
是一个接口,而不是一个类。因此,创建一个作为
HashSet
实例的对象,并将对该对象的引用分配给类型为Set
的变量。这是可行的,因为HashSet
类实现了 Set 接口。另一方面:给出编译错误,因为您无法创建接口的实例。
Java 接口本质上是实现(类)和使用它的事物之间的契约。它说明了符合对象的方法的名称和签名,但没有说明对象的状态或其方法如何工作。
(只是为了让事情变得有点混乱……Java 还允许您编写如下内容:
这不会创建
Set
接口本身的“实例”。 ..因为这没有意义。相反,它声明并实例化一个实现Set
接口的匿名类。)java.util.Set
is an interface, not a class. Socreates an object that is a
HashSet
instance, and assigns a reference to that object to a variable whose type isSet
. This works because theHashSet
class implements theSet
interface. On the other hand:gives a compilation error because you cannot create an instance of an interface.
An Java interface is essentially a contract between an implementation (a class) and the things that use it. It says what the names and signatures of a conforming object's methods are, but nothing about the object's state or how its methods work.
(Just to confuse things a bit ... Java also allows you to write something like this:
This is does not create an "instance" of the
Set
interface per se ... because that doesn't make sense. Rather, it declares and instantiates an anonymous class that implements theSet
interface.)以下是一些提示:
教程)
教程)
Java 教程)
您还应该阅读 Joshua Bloch 的《Effective Java》,尤其是第 52 条:“通过对象引用对象接口”(这里有一个小片段)
Here are some pointers:
Tutorial)
Tutorial)
Java Tutorial)
You should also read Effective Java by Joshua Bloch, especially item 52: "Refer to objects by their interfaces" (There's a small snippet viewable here)
java.util.Set
接口提供与java.util.HashSet
对象的松耦合。因此,开发人员可以将 java.util.Set 引用用于另一个 java.util.Set 接口系列对象。java.util.Set
interface provides the loose coupling withjava.util.HashSet
object. So developer can use thejava.util.Set
reference for anotherjava.util.Set
interface family object.引用
set
的类型为java.util.Set
,它是一个接口
。尽管它实际上指向java.util.HashSet
类型的对象。 (多态性)The reference
set
is of typejava.util.Set
which is aninterface
. Although it actually points to an object of typejava.util.HashSet
. (polymorphic)