Java: how to initialize child when super constructor requires parameter

Viewed 5785

I have

class A {

    int var;
    public A(int x) {
        var = x;
    }
}


class B extends A {
     int var2;

     public B(int x, int y) {
         super(...);
         var2 = y;
         x = f(y);
     }
 }

For the subclass B, I need to calculate the value x that is used in the constructor of A. If I were free to move super below my x=f(y) then I could pass in the result to the constructor of A (super). But super has to be the first line in the constructor of B.

Is there any way to initialize A with the proper value the first time? What if A.var were final and i couldn't go back and change it after construction?

Sure, I could put super(f(y)), but I could imagine cases where this would become difficult.

4 Answers
Related