I have some final fields in the class like
JavaScript
x
class A {
private final boolean a;
private final boolean b;
public A(boolean a){
this.a = a;
}
public A(boolean a, boolean b){
this.a = a;
this.b = b;
}
}
But this gives an error that final field ‘b’ might not have been initialized. So any help would be appreciated on how to handle final attributes initialization in case of multiple constructors. It works fine if I have only the second constructor.
Advertisement
Answer
You can initialize b to default false. All the final variable should be initialized in constructors.
JavaScript
public A(boolean a){
this.a = a;
this.b = false;
}
Or should call other constructors which would initialize them.
JavaScript
public A(boolean a){
this(a, false);
}
public A(boolean a, boolean b){
this.a = a;
this.b = b;
}