Static initialization error if placed before declaration

I noticed something in static initializers, which may be a bug in javac. I built a script where I can assign a variable a value but not read that value.

Two examples are given below: the first is compiled, the second gets an error when trying to read the value from tmp, but for some reason the assignment of the tmp value is allowed. I could understand if he couldn’t read or write the variable, since tmp is declared after the static initializer, but the error only for one of them does not make sense to me.

//Compiles Successfully: public class Script { public static Object tmp; static { tmp = new Object(); System.out.println(tmp); } } //error only on the read but not the assignment public class Script { static { tmp = new Object(); System.out.println(tmp); } public static Object tmp; } 

to emphasize this point, it compiles successfully.

 public class Script { static { tmp = new Object(); } public static Object tmp; } 
+6
source share
1 answer

This seems to be defined in the specification (see JLS 8.3.2.3 ):

The participant’s declaration must appear text before it is used only if the element is an instance (respectively static) field of class or interface C and all of the following conditions are true:

  • Use occurs in an instance (respectively static) initializer of a variable C or in an instance (respectively static) initializer
    from C.

  • Use is not on the left side of the quest.

  • Use is made using a simple name.

  • C is the innermost class or interface that spans usage.

So, if the use is on the left side of the assignment, then it is legal, since the second is no longer performed.

+3
source

Source: https://habr.com/ru/post/944451/


All Articles