This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
Is it possible to define as static an inner class that is declared within a method?
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
posted
0
No, a local class of a non-static method always is non-static, as far as I know.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Joyce's short answer is all you really need here. But Ilja's post would seem to raise the question: what about a local class declared in a static method? Answer: this is also non-static. You can't declare it as static, and it's not implicitly static, therefore it's still an inner class (just like a local class in a nonstatic method). However a local class declared in a static method is considered to be in a static context. Such a class is like a static nested class in that it has no access to nonstatic members of the enclosing class, and no access to a "this" reference for the enclosing class. (I.e. no OuterClass.this may be used.) However a local class in a static context is still considered an inner class, and shares other characteristics and limitations of inner classes - such as not being allowed to declare static members.
So, a local class in a static method is sort of a cross between a static nested class and a "traditional" (completely nonstatic) inner class. The JLS chose to describe it as an inner class with special rules. Which means, among other things, you can never declare a local class as static, even if it's declared inside a static method.
"I'm not back." - Bill Harding, Twister
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
posted
0
Jim, thanks for the clarification!
Philip Pomario
Ranch Hand
Joined: Oct 03, 2003
Posts: 113
posted
0
Thanks for all the great explanations, guys!
Philip Pomario
Ranch Hand
Joined: Oct 03, 2003
Posts: 113
posted
0
I just passed the SCJP1.4 exam and wanted to post this appreciation note to thank everyone who helped me understand Java a little better. Without your help this personal achievement wouldn't be possible.
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.