-
Why aren’t
finalvariables default initialized? Shouldn’t the default constructor initialize them to default values if you are happy with the constant be the default value. -
Why must you initialized them in the constructor at all? Why can you can’t you just initialize them before using them like other variables?
ex.
public class Untitled {
public final int zero;
public static void main(String[] args)
{
final int a; // this works
a = 4; // this works, but using a field doesn't
new Untitled();
}
}
Untitled.java:2: variable a might not have been initialized
- Why must you initialize
static finalvariables when they are declared? Why can’t you just initialize them before using them in any other method?
ex.
public class Untitled
{
public final static int zero;
public static void main(String[] args)
{
zero = 0;
}
}
Untitled.java:8: cannot assign a value to final variable zero
I’m asking these question because I’m trying to find a logical/conceptual reason why this won’t work, why it isn’t allowed. Not just because it isn’t.
The idea behind a
finalvariable is that it is set once and only once.For instance
finalvariables, that means they can only be set during initialization, whether at declaration, in a constructor, or an instance initialization block. For the variable to be set anywhere else, that would have to take place in a non-constructor method, which could be called multiple times – that’s why this is off limits.Similarly for
static finalvariables, they can only be set at declaration or in a static initialization block. Anywhere else would, again, have to be in a method which could be called more that once:As for your first question, I’m assuming it’s an error not to explicitly set a
finalvariable in order to avoid mistakes by the programmer.