A final instance variable can only be assigned a value at one of 2 times:
1. As an expression on the statement that defines it.
2. In a constructor.
That's the final (and there's no pun there) time you can assign a value. And the semantics of Java are that once a value has been assigned to a final variable, you can never assign to it again. That includes trying to re-assign it in a constructor (or a constructor invoking another constructor via "super" or "self"), and it includes assigning a value in a constructor if a value was already assigned on the definition.
Because of this, you absolutely, positively MUST assign the value to a final property before your constructor terminates - or if you aren't using a constructor, in the variable declaration. Because after that point, it's too late.
When it comes to destroying a civilization, gas chambers cannot hold a candle to echo chambers.
Regarding the assignment to a final instance variable in a constructor, I think that maybe it would be easier to think about this if instead of saying it needs to be assigned in a constructor (as one of the options), instead to say "in the construction of an instance".
The reason I think that is suppose you have two constructors which happen to not "interact":
Yes, this code compiles just fine and using the wording "...In a constructor..." sounds fine here.
However, the following code does not compile:
with the following compile error:
$ javac Test.java
Test.java:11: error: variable i might already have been assigned
i = 5;
The only way this code will compile again is if we do not attempt to assign to the final variable in the single-argument constructor:
So using the wording "in the construction of an instance" seems to me a better option.
posted 10 months ago
In the case using this(); which you showed, the variable i is actually initialised twice in one path of execution; the whole idea of final variables is that they must be initialised once.
I am Arthur, King of the Britons. And this is a tiny ad:
how do I do my own kindle-like thing - without amazon