Why do local inner classes not allow static variables ? The static fields of the classes could at least have been allowed access from the local method ?
Because static members make little sense when it comes to "local inner classes" since these classes belong to a scope as opposed to another class or a top level package. The "outer" world is not aware of this local inner class and always deals with instances of this class which are typically exposed via some sort of interface.
If there is any state that has to be maintained at the "local inner class" level, it can be easily done by doing the same at the enclosing method level. But probably the biggest reason might have to do with preventing the external entities from modifying the "class" level state of this inner class. Hence, only final primitives are allowed to be declared static when it comes to local inner classes.
class DamnIt {
void damnIt() {
class Test {
static boolean bb = false; // error; not final
final static boolean b = false; // works
final static Object o = new Object(); // error; not primitive
}
}
}
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
But like we normally have static fields in a normal class (there are so many uses of them), why can't we benefit from them in their local class ?
Do you have any scenario in mind which can be handled properly *only* if local inner classes are allowed to have static members?What is meant by "maintaining the state at the local class level" ? If its the state of the objects, how does allowing non-final static fields interfere with this maintenance ?
It does not interfere, it simply isn't required IMO.But modifying the static variables of a class may well be desired in some cases ?
In *which* cases? Also, why would modifying the state of a class which should ideally be visible to the declaring method be desired?
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734