Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing final variable in java constructor

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.

like image 869
Spasoje Petronijević Avatar asked Apr 20 '26 04:04

Spasoje Petronijević


2 Answers

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;
}
like image 88
sp00m Avatar answered Apr 21 '26 19:04

sp00m


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.

like image 20
Jason1 Avatar answered Apr 21 '26 17:04

Jason1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!