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

Per Bothner per at bothner.com
Tue Oct 11 09:18:49 PDT 2011


On 10/11/2011 02:28 AM, Ulf Zibis wrote:
>> 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?

I didn't have to - I've used this idiom numerous times.

But just to be sure: I did compile it.  I had to fix one typo:
Missing parens after 'new Foo'.

>> 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.

Of course, but it would be pretty rare (and ugly) for super(foo) to
have the kind of side-effects where the order would matter.

But I agree it is mot a general replacement.
-- 
	--Per Bothner
per at bothner.com   http://per.bothner.com/



More information about the coin-dev mailing list