3
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?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

2 Answers2

9

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.

AndrWeisR
  • 1,110
  • 11
  • 21
  • I see.. I thought that the scope of the function is inside the constructor so it did not make sense to me when this error popped up – FerociousPup Apr 06 '21 at 00:51
  • 3
    @FerociousPup but that method could be called outside of the constructor, the compiler isn't smart enough to know its only called in the constructor – wilmol Apr 06 '21 at 00:59
  • it's going to be possible to set it differently [in a future java version](https://stackoverflow.com/questions/64396802/who-calls-describeconstable-and-when) – Eugene Apr 06 '21 at 01:08
1

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.

PabloBuendia
  • 263
  • 1
  • 12