public class A { private static final int x; public A() { x = 5; } }
final
means the variable can only be assigned once (in the constructor).static
means it's a class instance.I can't see why this is prohibited. Where do those keywords interfere with each other?
If you declare a static variable in a class, if you haven't initialized it, just like with instance variables compiler initializes these with default values in the default constructor. Yes, you can also initialize these values using the constructor.
The only way to initialize static final variables other than the declaration statement is Static block. A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.
In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.
A constructor will be called each time an instance of the class is created. Thus, the above code means that the value of x will be re-initialized each time an instance is created. But because the variable is declared final (and static), you can only do this
class A { private static final int x; static { x = 5; } }
But, if you remove static, you are allowed to do this:
class A { private final int x; public A() { x = 5; } }
OR this:
class A { private final int x; { x = 5; } }
static final variables are initialized when the class is loaded. The constructor may be called much later, or not at all. Also, the constructor will be called multiple times (with each new object ), so the field could no longer be final.
If you need custom logic to initialize your static final field, put that in a static block
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With