Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 968
FerociousPup Avatar asked May 28 '26 00:05

FerociousPup


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.

like image 60
AndrWeisR Avatar answered May 30 '26 16:05

AndrWeisR


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.

like image 23
PabloBuendia Avatar answered May 30 '26 16:05

PabloBuendia



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!