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

Per Bothner per at bothner.com
Mon Oct 10 17:54:29 PDT 2011


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();
          }
     }

or:

     class A extends Base {
          A() { super(specialFoo()); }
          private static Foo specialFoo() {
              Foo foo = new Foo;
              foo.special_init();
              return foo; }
         }
     }
-- 
	--Per Bothner
per at bothner.com   http://per.bothner.com/



More information about the coin-dev mailing list