Here is example code:
class A {
static {
int a;
class B {
}
}
public static void main(String[] args){
// cannot access class B and in a;
}
}
I don’t know what the static keyword in this context means. I declare an int variable and a class inside it. But I cannot use it inside class A or in the main method. I compile and it doesn’t produce any errors. So, I think this type of declaration has some purpose.
This is a static initialization block. You can use this to collect initialization for static/class members.
Similarly you can have a non-static initialization block to initialize instance members for each new object:
This example is trivial, you could instead just initialize the variables in their declaration:
static int a = 5, and in fact generally that would be clearer. But use an initialization block when the initialization is multi-step, or generally more complicated, for example, setting up a database connection.For more examples, see: Initializing Fields from the java tutorials.