Static Blocks and Variables

Why is the value of a valid static variable assigned in the code below, but not using the same variable?

class Test { static { var=2; //There is no error in this line System.out.println(var); //Why is there an error on this line if no error on the above line } static int var; } 
+6
source share
3 answers

Because usage is not on the left side of the assignment , as described below:

From section 8.3.2.3 JLS, Restrictions on the use of fields during initialization :

A member declaration must appear before its use only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions are true:

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

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

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

A compile-time error occurs if any of the three requirements above are not satisfied.

+2
source

Error: Test.java:6: illegal forward reference . Move int var in front of the static block.

+3
source

Try it like this:

 class Test { static int var; static { var=2; //There is no error in this line System.out.println(var); //Why is there an error on this line if no error on the above line } } 

With announcement before use

0
source

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


All Articles