Inner static class in Java
What is benefit of using an inner stati开发者_开发知识库c 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.
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.
精彩评论