Why does this() and super() have to be the first statement in a constructor?

Ulf Zibis Ulf.Zibis at gmx.de
Tue Oct 11 02:28:42 PDT 2011


Am 11.10.2011 02:54, schrieb Per Bothner:
> On 10/08/2011 05:55 AM, Lenik wrote:
>> +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.
>>        }
> What is wrong with:
>
>       class A extends Base {
>            A() { this(new Foo); }
>            private A(Foo foo) {
>                super(foo);
>                foo.special_init();
>            }
>       }
Seems great, did it compile?

> or:
>
>       class A extends Base {
>            A() { super(specialFoo()); }
>            private static Foo specialFoo() {
>                Foo foo = new Foo;
>                foo.special_init();
>                return foo; }
>           }
>       }
In the original example, super(foo) is executed *before* foo.special_init(), so in most cases this 
workaround would have different result, i.e. is not compatible.

-Ulf




More information about the coin-dev mailing list