Inner static class in Java

2019-04-06 20:29发布

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

And how is its memory allocated?

3条回答
Melony?
2楼-- · 2019-04-06 21:00

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.

查看更多
来,给爷笑一个
3楼-- · 2019-04-06 21:06

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.

查看更多
来,给爷笑一个
4楼-- · 2019-04-06 21:14

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.

查看更多
登录 后发表回答