简体   繁体   English

Java中的内部静态类

[英]Inner static class in Java

What is benefit of using an inner static class? 使用内部静态类有什么好处? Where should I prefer it over other options? 我应该在哪里选择其他选项呢?

And how is its memory allocated? 它的内存如何分配?

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. 但是,如果将内部类设为私有,则不能在该类之外使用它。

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. 在这种情况下,我们可以将Department类作为University类的内部类。

And how is its memory allocated? 它的内存如何分配?

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. 关于这个类的实例或类的静态成员,这种情况没有什么特别之处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM