Inner static class in Java
Asked Answered
B

3

9

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

And how is its memory allocated?

Biased answered 15/11, 2010 at 9:24 Comment(1)
possible duplicate of Static nested class in Java, why?Registrant
T
7

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.

Tartaglia answered 15/11, 2010 at 9:25 Comment(0)
D
5

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.

Deliberation answered 15/11, 2010 at 10:41 Comment(0)
H
4

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.

Helfant answered 15/11, 2010 at 11:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.