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 var
is 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.
class B extends A {
int var2;
public static B createB(int x, int y) {
x = f(y);
return new B(x, y);
}
public B(x, y) {
super(x);
this.var2 = y;
}
}
something like that. You have no choice, as explicit constructor invocation must happen on the first line of the wrapping constructor.
You can do it like this :
class B extends A {
int var2;
public B(int x, int y) {
super(calculateX(y));
var2 = y;
}
private static int calculateX(int y) {
return y;
}
}
Calling a static method is the only thing you can do before calling the superclass constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With