Lets say I have a situation like this.
private final A a;
private final B b;
private final C c;
private ClassX(){
this.c = createCSomehow();
}
public ClassX(A a){
this();
this.a = a;
this.b = null;
}
public ClassX(B b) {
this();
this.b = b;
this.a = null;
}
Why Idea is complaining about a and b property? Idea underline them and say: Variable a might not have been initialized. I am sure that I have no more constructors and that in every case a will be populated with some value.
I don't really know how to properly answer the why (JLS investigation needed), but for the how, the following should compile:
private final A a;
private final B b;
private final C c = createCSomehow();
public Main(A a){
this.a = a;
this.b = null;
}
public Main(B b) {
this.b = b;
this.a = null;
}
As per the JLS specs http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.3.1.2
A blank final instance variable must be definitely assigned (§16.9) at the end of every constructor (§8.8) of the class in which it is declared; otherwise a compile-time error occurs. This is why Idea is complaining.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With