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.
Also, because an inner class is associated with an instance, it cannot define any static members itself. Objects that are instances of an inner class exist within an instance of the outer class.
Mainly, static blocks are used to initialize the class/static variables if you have not initialized them at the time of declaration. In case of interfaces when you declare a field in it. It is mandatory to assign value to it else, a compile time error is generated.
Instance variables are initialized using initialization blocks. However, the static initialization blocks can only initialize the static instance variables. These blocks are only executed once when the class is loaded.
A Static Initialization Block in Java is a block that runs before the main( ) method in Java. Java does not care if this block is written after the main( ) method or before the main( ) method, it will be executed before the main method( ) regardless.
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.
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 {...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With