Is there a good way to maintain a reference to an object created in a constructor that needs to be passed to the super constructor of some extended class (other than making it accessible from the super class or passing it into the constructor as a parameter)?
Let me clarify with an example. Take this class (which I can't modify and which doesn't give me access to foo):
class TestA {
TestA(Object foo) {}
}
Now, I would like to extends this class as follows:
class TestB extends TestA {
Object myCopyOfFoo;
TestB() {
super(new Object());
}
}
Is there a good way to store the created new Object()
in myCopyOfFoo
?
Neither one of these three ideas work:
TestB() {
myCopyOfFoo = new Object();
super(myCopyOfFoo);
}
(Error: Constructor call must be the first statement in a constructor)
TestB() {
super(myCopyOfFoo = new Object());
}
(Error: Cannot refer to an instance field myCopyOfFoo while explicitly invoking a constructor)
TestB() {
super(makeFoo());
}
Object makeFoo() {
myCopyOfFoo = new Object();
return myCopyOfFoo;
}
(Error: Cannot refer to an instance method while explicitly invoking a constructor)
I guess I could do the following, but it's neither thread-safe nor elegant:
static Object tempFoo;
TestB() {
super(tempFoo = new Object());
myCopyOfFoo = tempFoo;
}
Does anyone have a better idea for me? And why on earth are my first two ideas not legit?