什么时候使用嵌套的 Java 类真的有用? [英] When is really useful to use a nested Java class?
问题描述
你能给我一个具体的例子,说明嵌套的 java 类是有用的吗?我正在研究它,我了解它的工作原理,但我无法想象真正有必要使用它的真实情况.
Could you give me a concrete example where a nested java class is useful? I am studying it, I understand how it works but I can not imagine a real situation where its use is really necessary.
非常感谢
马可
推荐答案
关于何时使用嵌套类的最简洁的总结是:当该类在逻辑上属于外部类的 API 时,或者何时封装特定于外部类的行为.
The most concise summary of when to use a nested class is: when that class is logically part of the outer class' API, or when it encapsulates behavior specific to the outer class.
例如,Map.Entry
:它是映射中的一个条目.它在逻辑上是 Map
的 API 的一部分,所以把它放在 Map
中是有意义的.
For example, Map.Entry
: it's an entry in a mapping. It's logically part of Map
's API, so it makes sense to put it inside Map
.
另一个常见示例是 Builder 类:您使用 Builder
制作一个东西,所以把它放在那个东西里面是有意义的.
Another common example is Builder classes: you use a Builder
to make a thing, so it makes sense to put it inside that thing.
这些是您仅在使用外部类的上下文中真正使用的类:有时您可能会将 Map.Entry
本身用作某种配对类;有时您可能想单独使用 Builder
,例如作为方法的参数,该方法将事物放入该构建器中,但实际上并不构建本身.这些情况可能与也使用外部类的代码相去甚远:您仍在使用外部类的 API 的某些方面,因此它们在逻辑上仍然属于该 API.
These are classes that you only really use in the context of using the outer classes: sometimes you might use a Map.Entry
by itself as some sort of pair class; and sometimes you might want to use a Builder
by itself, for example as a parameter to a method which puts things into that builder, but doesn't actually do the building itself. These cases are probably rarely far from code that also uses the outer class too: you're still using some aspect the outer class' API, so they do still logically belong to that API.
您可以将此类类与主"类一起放在顶层.您可能不想这样做的原因有几个:
You could put such classes at the top level, alongside the "main" class. There are a few reasons why you might not want to do this:
- 它使命名空间变得混乱.如果你有
Foo
、Bar
、Baz
等类,还有FooBuilder
、BarBuilder
,BazBuilder
在顶层只会让我们更难看到有用的"顶层类.- Google 的协议缓冲区 为每个生成一个
Builder
类消息类型.考虑到 Google 代码中使用的协议缓冲区的数量,这种混乱会太麻烦.
- It clutters the namespace. If you've got classes
Foo
,Bar
,Baz
etc, havingFooBuilder
,BarBuilder
,BazBuilder
at the top level just makes it harder to see the "useful" top level classes.- Google's protocol buffers generate a
Builder
class for every message type. Given the number of protocol buffers used in Google code, this clutter would be far too cumbersome.
您还可以使用它们来封装类中的内部逻辑或中间状态:例如,当我发现自己在类中的私有方法之间传递相同的 N 个参数时,我喜欢定义私有嵌套类.这是您不希望班级以外的人关心的事情;只是在课堂上方便.
You can also use them to encapsulate internal logic or intermediate state in the class: for example, I like to define private nested classes when I find myself passing around the same N parameters between private methods in a class. This is stuff that you don't want people outside your class to care about; it's merely convenient inside the class.
这篇关于什么时候使用嵌套的 Java 类真的有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Google's protocol buffers generate a
- Google 的协议缓冲区 为每个生成一个