本文介绍了Bloch有效的Java-与非静态相比,更喜欢静态类-多少个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道封闭类可以创建多少个静态成员类实例.我仅假设一个,但是从Bloch提取的以下摘录对我来说没有意义.

I want to know how many instances of a static member class can be created by the enclosing class. I assume one only, but then the following extract from Bloch doesn't make sense to me.

引用Joshua Bloch的有效Java-项目22 *:偏爱静态成员类而不是非静态成员类.

Quoting Joshua Bloch's Effective Java - Item 22*: Favor static member classes over nonstatic.

他指出,地图为地图中的每个键值对创建了一个Entry对象,即,静态成员类的多个实例.

He states that the map creates an Entry object for each key-value pair in the map, i.e. multiple instances of the static member class.

所以我的假设是错误的!这意味着我对静态成员类的理解是错误的.每个人都知道静态成员变量的行为,例如经典的静态最终字符串-对象只有一个实例.

So my assumption is wrong! That means my understanding of static member classes is wrong. Everyone knows how a static member variable behaves, the classic static final string for instance - there is only one instance of the object.

这是否意味着在实例化封闭对象时实际上并未实例化静态成员类?

Does this mean then that a static member class is not actually instantiated when the enclosing object is instantiated?

在这种情况下,使用静态成员类作为Entry的Map有什么意义?为什么不只在API上使用接口?然后,每个其他Collections类都可以提供自己的实现.

Well in that case, what's the point of Map using a static member class for Entry? Why not just use an interface on the API? Every other Collections class could then just provide it's own implementation.

[*]刚刚意识到这是我所拥有的PDF版本中的第18项

[*] Just realised that it's item 18 in the PDF version of the book I have

推荐答案

我认为Java团队搞砸了这一名称.静态内部类(严格来说,它们的正确名称是静态嵌套类")与普通类没有什么不同,只不过它具有精美的名称(Something.MyClass而不是MyClass)并且可以设为私有(即,非私有).可以从其他类实例化).

I think the Java team messed up the naming on this one. A static inner class (strictly speaking their correct name is "static nested class") is in no way different from an ordinary class except it has a fancy name (Something.MyClass instead of MyClass) and can be made private (i.e. not instantiable from other classes).

Map的情况下,仅选择它是因为名称Map.Entry清楚表明EntryMap有关.正如您所建议的,为此使用一个普通的类是完全合理的.唯一的区别是您不必编写Map.Entry.

In case of Map, it was solely chosen because the name Map.Entry makes it clear that Entry relates to Map. As you suggest, it would have been perfectly reasonable to just use an ordinary class for this. The only difference is you don't get to write Map.Entry.

我认为他们应该做的是为静态嵌套类使用非静态"内部类(即封闭类中的class)的语法,而不是发明一个新关键字来创建非静态"内部类.静态"内部类,因为这些类的行为与普通类不同.也许像attached class之类的东西. AFAIK选择了static关键字是为了避免保留关键字过多,但我认为这只会引起混淆.

I think what they should have done is to use the syntax for "non-static" inner classes (i.e. just class in an enclosing class) for static nested classes, and instead invent a new keyword to create "non-static" inner classes, because it's these that behave different from normal classes. Maybe something like attached class. AFAIK the keyword static was chosen in order to avoid having too many reserved keywords, but I think it just encouraged confusion.

这篇关于Bloch有效的Java-与非静态相比,更喜欢静态类-多少个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 01:49