Directly within class
, a block is an instance 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.