Java中的内部静态类
使用内部静态类有什么好处?与其他选项相比,我应该在哪些方面更喜欢它?
它的内存是如何分配的?
What is benefit of using an inner static class? Where should I prefer it over other options?
And how is its memory allocated?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果内部类是静态的,则不需要外部类的实例来实例化它。
如果内部类是公共的,那么它基本上只是一种名称范围技术,用于强调该类“属于”外部类这一事实。
但是,如果将内部类设为私有,则不能在该类之外使用它。
If the inner class is static, you don't need an instance of the outer class to instantiate it.
If the inner class is public, it's basically just a name-scoping technique for highlighting the fact that the class "belongs" to the outer class.
If you make the inner class private however, it can't be used outside of that class.
使用内部类最引人注目的原因之一是组合。在组合的情况下,一个实体的存在仅仅是为了其更高实体的目的。例如大学。大学由院系组成。这些院系在大学之外没有单独的存在。此外,进入院系的权限应由大学控制。在这种情况下,我们可以将 Department 类作为 University 类的内部类。
One of the most compelling reasons for using inner classes is composition. In case of composition the existence of one entity is solely for the purpose of its higher entity. For example a University. A university is composed of Departments. The departments has no individual existence outside the university. Moreover, the access to departments should be controlled by University. In this case, we can have the Department class as an inner class of the University class.
简单的答案是,内部静态类的内存分配方式与非嵌套类相同。这种情况没有什么特别的,无论是对于类的实例还是类的静态成员。
The simple answer is that memory for an inner static class is allocated the same way as for a non-nested class. There is nothing special about this case, either with respect to instances of the classes or static members of the class.