<< Sea Island Mathematical Manual (海岛算经) | Home | Holliday Java Quiz: ConcurrentModificationException >>

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

It doesn't work, but what's the point?

Re: Friday Java Quiz: Static Fields In Inner Classes

No. You can have static fields in nested classes, however. I think it's more surprising to most Java developers that you can nest classes in interfaces.

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

it could work if the inner class was static IIRC

Re: Friday Java Quiz: Static Fields In Inner Classes

Can anyone please explain why statics are not allowed in inner classes? Is there any real technical problem problem with such a construct?

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:
class Pippo {
  static class Pluto {
    static Integer foo = 10;
  }
}

Re: Friday Java Quiz: Static Fields In Inner Classes

Funny, I didn't find a way to edit my comment and I'd accidentally hit a submit button. Anyways, replying to Bob Lee. IIRC, an enum element is realized as an anonymous static nested, rather than inner 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!

Add a comment Send a TrackBack