Reputation: 33
I have just started reading Java. One thing I find confusing is that a blank final variable should be initialized in all constructors of a class. If I have a class with 3 constructors and I initialise a blank final variable in one constructor, why do I need to initialise the same blank final variable in other two constructors also ?
Upvotes: 2
Views: 241
Reputation: 393791
The final variable must be initialized by the time an instance of the class is created (i.e. after the constructor execution is done).
If you create an instance of the class using one of the constructors that don't initialize the blank final variable, the final variable won't be initialized once the constructor's execution is done.
Therefore all constructors must initialize the blank final variable.
This is assuming none of the constructors is calling a different constructor using this()
.
J.L.S Chapter 16. Definite Assignment
Each local variable (§14.4) and every blank final field (§4.12.4, §8.3.1.2) must have a definitely assigned value when any access of its value occurs.
If you create an instance of your class using a constructor that doesn't initialize the blank final field, you might access that field before it was assigned. Therefore the compiler doesn't allow it.
Upvotes: 4
Reputation: 1982
This is because only one constructor is executed when an instance of your class is created.
I prefer to have one constructor which serves as the most common constructor, and call this from the other constructors. In one constructor, you can call another constructor of the same class via this(...)
. Example:
class MyClass {
private final int a;
private final String b;
private double c;
/**
* Most common constructor.
*/
public MyClass(int a, String b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public MyClass(int a, String b) {
this(a, b, 0.0);
}
public MyClass(double c) {
this(0, null, c);
}
// other constructors as needed
}
This way, you have focused the responsibility to initialize the instance in one constructor. The other constructors rely on that one.
Upvotes: 0