Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can you not use an initializer block for a static variable in an inner class? [duplicate]

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.

like image 318
acushner Avatar asked Sep 22 '15 19:09

acushner


People also ask

Can we have static variable in inner class?

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.

Why static blocks are not allowed in interface?

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.

Can we initialize variable in static block Java?

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.

Why do we need static initializer block?

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.


2 Answers

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.

like image 79
rgettman Avatar answered Oct 10 '22 18:10

rgettman


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 {...}
like image 41
Peter L Avatar answered Oct 10 '22 17:10

Peter L