Complaint against final variable

final, java

Solution

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`: -

public static void main(String[] args) {
    FinalTest obj = new FinalTest(something);

    obj.setStuff(something); // There you go. This cannot be prevented. 
}

See JLS - Definite Assignments for detailed explanation on this.

Problem

Okay, so as far as I know, I understand these things about a `final` variable. - It should be assigned only once - All the `final` variables 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?

Original source