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?
where getName() is a static function that gets you the name.
In that case, you might as well make it static, too. And Java convention is to name such constants in ALL_CAPS.
Another possiblity is to initialize the field in an instance initializer blocK:
In this case, you can mark the field as 'static' also.
Do the initialization in the constructor, e.g.,
Of course, if you actually know the value at variable declaration time, it makes more sense to make it a constant, e.g.,
We're getting away from the question.
Yes, you can use a
private final
variable. For example:What this means is that the Account class has a dependency on the two Strings, account and routing numbers. The values of these class attributes MUST be set when the Account class is constructed, and these number cannot be changed without creating a new class.
The 'final' modifier here makes the attributes immutable.