简体   繁体   中英

Static blocks and variables

Why in the below code is assigning a value to the static variable acceptable but using that same variable is not?

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;
}

The error you get is Test.java:6: illegal forward reference . Move the int var before the static block.

Because the usage is not on the left hand side of an assignment , as explained below:

From section 8.3.2.3 of the JLS, Restrictions on the use of Fields during Initialization :

The declaration of a member needs to appear before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:

  • The usage occurs in an instance (respectively static) variable
    initializer of C or in an instance (respectively static) initializer
    of C.

  • The usage is not on the left hand side of an assignment.

  • C is the innermost class or interface enclosing the usage.

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

Try 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 the declaration before the use

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM