Java – why can’t the final static variable be assigned in the instance block?
class Test {
class Test { static final String name; { name = "User"; /* shows error. As i have to assign User as default value */ } final String name1; { name1 = "User"; // This works but why the above one does not works } }
I can use static blocks to allocate values, but I can't block them by instance. Why?
Solution
Because it is static final, it must be initialized once in a static context - declaring variables or in a static initialization block
static { name = "User"; }
Edit: static members belong to this class and non - static members belong to each instance of this class If you want to initialize a static variable in an instance block, it will be initialized every time you create a new instance of the class This means that it will not be initialized before and can be initialized multiple times Because it is static and final, it must be initialized once (for this class, not once per instance), so your instance block will not
Maybe you want to learn more about static vs. non static variables in Java
Edit2: the following are examples that may 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 uncommented lines are valid If we have
// instance block { b++; // increment every time an instance is created // ... }
Then B will be the counter for the number of instances created because it is static and incremented in the non - static instance block