Cannot assign value to a final variable in method called inside constructor

Viewed 494
class A {
    private final int t1;
    private final int t2;

    public A(int c1, int c2) {
        t1 = c1;
        initT2(c2);
    }

    private void initT2 (int c2) {
        try { 
            t2 = c2;
        } catch (...) {}
    }
}

t1 gets initialized but t2 does not. Cannot assign a value to final variable 's3Client' is the error.

If I shift the body of the function initT2 inside the constructor, it works. Why doesn't it work outside the constructor when it is being called from inside the constructor?

2 Answers

It's just a rule of Java - you can initialise final variables inside a constructor, or when it's declared, or in a static initialiser, but not in code outside of the constructor such as your initT2 method.

I think the biggest danger would be that, if the method gets overridden by a subclass, it could potentially erase the declaration of the final variable.

That's why it needs to be only declared in the constructor or on the class, or on a static block, so there's no way of not initializing the variable.

Related