Is there a solution to use a final variable in a Java constructor? The problem is that if I initialize a final field like:
private final String name = "a name";
then I cannot use it in the constructor. Java first runs the constructor and then the fields. Is there a solution that allows me to access the final field in the constructor?
This is not correct, fields are evaluated first, otherwise you couldn't access any default values of members in your constructors, since they would not be initialized. This does work:
The keyword final merely marks the member constant, it is treated as any other member otherwise.
EDIT: Are you trying to set the value in the constructor? That wouldn't work, since the member is immutable if defined as final.
I do not really understand your question. That
executes as follows:
Marking it static, will allow you to use it in the constructor, but since you made it final, it can not be changed.
is is possible to use a static init block as well.
If you are trying to modify the value in the constructor, then you can't assign a default value or you have to make it not final.
or