Inner static class in Java

痴心易碎 提交于 2019-12-09 16:20:00

问题


What is benefit of using an inner static class? Where should I prefer it over other options?

And how is its memory allocated?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/4182952/inner-static-class-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!