Why does this() and super() have to be the first statement in a constructor?
Ulf Zibis
Ulf.Zibis at gmx.de
Sat Oct 8 07:43:44 PDT 2011
class A extends Base {
A() {
// ERROR:
Foo foo = new Foo();
super(foo);
foo.special_init();
// Workaround: (would work, if we would have method invocation chaining:
//
http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/001180.html)
super(__lastFoo.set(new Foo()).get());
__lastFoo.get().special_init();
}
// Need to make it thread-local to avoid concurrent access.
private static final ThreadLocal<Foo> __lastFoo = new ThreadLocal<Foo>();
}
-Ulf
Am 08.10.2011 14:48, schrieb BODZ, Domain:
> +1, I've also had this problem for many times. Static helper doesn't always work, see this example:
>
> class Base {
> /* foo is private and unreadable, no getter anyway. */
> private final Foo foo;
>
> Base(Foo foo) { this.foo = foo; }
> }
>
> class A extends Base {
> A() {
> // ERROR:
> Foo foo = new Foo();
> super(foo);
> foo.special_init();
>
> // Workaround:
> super(__lastFoo = new Foo());
> Foo foo = __lastFoo;
> foo.special_init();
> }
> static Foo __lastFoo; // XXX Need to make it thread-local to avoid concurrent access.
> }
>
> -Xie Jilei
>
>
> On Sat, Oct 8, 2011 at 7:28 PM, Ulf Zibis <Ulf.Zibis at gmx.de <mailto:Ulf.Zibis at gmx.de>> wrote:
>
> Anyway,
> int c = a + b;
> doesn't affect any object field initialization.
> It's just a local variable, which gets lost after the instance is instantiated.
>
> As workaround, you can always use a static helper method which does the same:
> super(staticHelper(a, b));
>
> So I agree, it would reasonable, to allow some code in advance of this() or super().
>
More information about the coin-dev
mailing list