Okay, so as far as I know, I understand these things about a final variable.
- It should be assigned only once
- All the
finalvariables should be initialized before the constructor completes
Now using the above, I do not understand how the below doesn’t work:
public class FinalTest implements AnotherClass {
private final Something something;
private final otherthing;
@Override
public void setStuff(Something something) {
this.something = something;
this.otherthing = new SomeClass(something);
}
public FinalTest(Something something) {
setStuff(something);
}
}
Here, before the constructor completes the final variables are being set. So why does the compiler complain against it?
It’s not necessary that your method gets called only from constructor, it can be called from outside your constructor also. And even a second call might be added to the same constructor in future also.
Even though you might not have used it now, but Compiler cannot be sure about it, so it does not allow it. In technical term, there is no
definite assignment.For e.g: – suppose you instantiate your class from
main: –See JLS – Definite Assignments for detailed explanation on this.