Friday Java Quiz: Static Fields In Inner Classes
(Mario Aquino suggested this quiz.)
Q: Will the following Java source compile?
public class Outer { public class Inner { public static int ONE = 12; } }
Strict rules: No actually running the compiler.
Re: Friday Java Quiz: Static Fields In Inner Classes
No, but what's funny is this is allowed at the bytecode level. Actually, enum switch statements are converted to a local class with static state.
I've never fully understood why this isn't allowed. My understanding is that you semantically have a class per instance, so the lang guys thought static state could be confusing.
Re: Friday Java Quiz: Static Fields In Inner Classes
"...so the lang guys thought static state could be confusing."
I think that's it. If it were allowed, would the static variable be at the scope of the parent instance (i.e. act like a member of the parent) or be (basically) global like normal static variables? I don't think there's an obvious correct answer. The former is probably semantically correct but would make the language significantly more complex IMO.
Re: Friday Java Quiz: Static Fields In Inner Classes
The inner class has access to all fields/methods of the parent class. Non-static inner classes are meant to be accessed from inside/instances of the parent class. Hence static variables defined in the inner class serve no additional purpose. They perform similarly as if defined in the parent class.
Re: Friday Java Quiz: Static Fields In Inner Classes
You can have static members in static inner classes as 'Anonymous' commented:
AND you CAN have static fiels in Inner Classes if those fields are 'final':
public class Outer
{
public class Inner
{
public static final int PLUTO = 5;
}
}
That's how an inner enum it's finally compiled!