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.
Assuming
varis private and you need to set the value with the constructor (which seems to be the point of the question, otherwise there are many easy solutions), I would just do it with a static factory-like method.something like that. You have no choice, as explicit constructor invocation must happen on the first line of the wrapping constructor.