Because it is static final
, so it must be initialized once in the static context -- when the variable is declared or in the static initialization block.
static {
name = "User";
}
EDIT: Static members belong to the class, and non-static members belong to each instance of that class. If you were to initialize a static variable in the instance block, you would be initializing it every time you create a new instance of that class. It means that it would not be initialized before that, and that it could be initialized multiple times. Since it is static
and final
, it must be initialized once (for that class, not once for each instance), so your instance block will not do.
Maybe you want to research more about static vs. non-static variables in Java.
EDIT2: Here are examples that might help you understand.
class Test {
private static final int a;
private static int b;
private final int c;
private int c;
// runs once the class is loaded
static {
a = 0;
b = 0;
c = 0; // error: non-static variables c and d cannot be
d = 0; // referenced from a static context
}
// instance block, runs every time an instance is created
{
a = 0; // error: static and final cannot be initialized here
b = 0;
c = 0;
d = 0;
}
}
All non-commented lines work. If we had
// instance block
{
b++; // increment every time an instance is created
// ...
}
then b
would work as a counter for the number of instances created, since it is static
and incremented in the non-static instance block.