+ 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?
4 Respostas
+ 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
+ 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. :)
+ 2
Static variables and static methods can access each other.
- 2
Yes, an inner class can only exist