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

Lenik lenik at bodz.net
Sat Oct 8 05:55:33 PDT 2011


+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 10/08/2011 07:28 PM, Ulf Zibis 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().
>
> + 1 for your proposal, Vimil Saju.
>
> -Ulf
>
>
>
> Am 08.10.2011 01:39, schrieb Daniel Yokomizo:
>> On Oct 7, 2011 1:58 PM, "Paul Benedict"<pbenedict at apache.org>   wrote:
>>> It's a compiler error because the superclass is guaranteed to be
>>> initialized first before the subclass.
>> Not guaranteed by the JVM, as in anonymous inner classes.
>>
>>> On Fri, Oct 7, 2011 at 11:51 AM, Vimil Saju<vimilsaju at yahoo.com>   wrote:
>>>> If you have subclass then java requires that this() or super has to be
>> first statement in the constructor of the subclass.
>>>> Here is an example
>>>>
>>>> publicclassMyClass{
>>>>           publicMyClass(intx){}
>>>> }
>>>>
>>>> publicclassMySubClassextendsMyClass{
>>>>           publicMySubClass(inta,intb){
>>>>                   intc =a +b;
>>>>                   super(c); // COMPILE ERROR
>>>>           }
>>>> }The above compilation error can be resolved by rewriting the code in
>> the constructor as follows
>>>> publicclassMySubClassextendsMyClass{
>>>>           publicMySubClass(inta,intb){
>>>>                   super(a + b);
>>>>           }
>>>> }Can't the Java compiler detect that in the previous code there was no
>> access to the instance fields or methods and therefore allow the code to
>> compile without any error.




More information about the coin-dev mailing list