6

why does java not allow static declarations with a static initialization block in a non-static inner class?

in the below code, outer2 will work and inner2 will not, despite doing the same thing. any ideas? i'm not looking for a workaround, i'm just trying to understand why java fails to do this.

public class WhyUNoStatic {
    public static final String outer1 = "snth";  // ok
    public static final String outer2;  // ok
    static
    {
        outer2 = "snth";
    }

    public class Inner {
        public static final String inner1 = "snth";  // still ok! 
        public static final String inner2;  // FAILURE TIME
        static
        {
            inner2 = "snth";
        }
    }
}

edit: note that inner1 will work fine. it's not that java prohibits static vars in inner classes, it just prohibits declarations of them.

acushner
  • 9,595
  • 1
  • 34
  • 34

2 Answers2

2

The JLS, Section 8.1.3, disallows this behavior.

It is a compile-time error if an inner class declares a static initializer (§8.7).

It is a compile-time error if an inner class declares a member that is explicitly or implicitly static, unless the member is a constant variable (§4.12.4).

You declared your static variables final in your inner class, which is ok, but the static initializer is prohibited there.

Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • And as for the reason why, it probably would've complicated the already quite complicated initialisation sequence even more. – biziclop Sep 22 '15 at 19:49
  • yeah, that's what i'm trying to get at. why can the compiler not handle this? i'd love to see a code example to show why it's difficult for the compiler to deal with this... – acushner Sep 22 '15 at 21:39
2

See JLS Chapter 8

Inner classes may not declare static initializers (§8.7) or member interfaces, or a compile-time error occurs.

You can declare a nested class instead

public static class Inner {...}
Peter L
  • 302
  • 1
  • 6