Are Java inner class and static nested class different? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 32

Are Java inner class and static nested class different?

If yes, when should I use each of them? is there any special pattern for them?

23rd May 2018, 6:32 PM
Amir
Amir - avatar
4 Answers
+ 4
Yes, an inner class can only exist within an existing instance of the enclosing class, so you have to make the outer class object first. A static nested class can be accessed.. statically. The latter is useful for encapsulation, as well as convenience. For example, if you add a 'builder' to a class you can add a static inner class which has access to the private member variables of the outer class. I haven't needed to use a non static nested class for a while, I can only think of when I was doing some Android stuff and you might make an AsyncTask inner class which you would only ever want when the enlosing (activity) class was being used. So this inner class is treated like another member of the class - dependent on, and usable only within, an enclosing instance
23rd May 2018, 10:06 PM
Dan Walker
Dan Walker - avatar
+ 6
You can see a lot of nested inner classes when prototyping (reversed builder) complex junits, when initialization logic pollutes test, but due to objects composition it is better to not create "normal" class. Basically the rest is just like Dan said. :)
24th May 2018, 10:59 PM
Jakub Dubański
Jakub Dubański - avatar
+ 2
Static variables and static methods can access each other.
25th May 2018, 8:00 AM
Apple Blossom
Apple Blossom - avatar
- 2
Yes, an inner class can only exist
24th May 2018, 7:02 AM
Sujit Roy
Sujit Roy - avatar