简体   繁体   中英

Static variable in an anonymous block in java

Why can't we initialize a static variable in an anonymous block in java? For eg : Why doesn't this code compile?

public class A {
  {
      static int a = 1;
  }
}

I get this compile error saying

Illegal modifier for the variable a; only final is permitted

Why only final?

Directly within class , a block is aninstance initializer block . You can't declare static variables in an instance initializer block. Simply remove it from the block:

public class A {
    static int a=1;
}

Instance initializer blocks are called when instances are created, prior to the code in any instance constructors. So it makes sense you can't declare members there (static or otherwise). They're code, as though inside a constructor. Example:

import java.util.Random;

public class Example {
    private String name;
    private int x;
    private int y;

    {                                     // This is the
        this.x = new Random().nextInt();  // instance
        this.y = this.x * 2;              // initializer
    }                                     // block

    public Example() {
        this.name = null;
    }

    public Example(String name) {
        this.name = name;
    }
}

In the above, regardless of which constructor is used, the first thing that happens is the code in the instance initializer block, followed by the code in the constructor that was used.

There are also static initializer blocks, which do the same thing for static stuff when the class is loaded. They start with the keyword static , more in the link above.

From the docs of

Initialization blocks

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

The code you wrote will moved to constructor. A static member local to the constructor won't make much sense they must be declared at class level and not local to the constructor

And you are seeing in the error message only final is permitted , because you can modify the final variables in constructor if you haven't yet initialize them at the time of declaration.

{
      static int a=1;
}

you can't have static modifier in a code block , a here is just a local variable

you can do static field initialization in a static block. But not the declaration.

public class A{
  static int a;
  static
  {
    a = 1;
  }
}

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