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

前端 未结 21 1929
北荒
北荒 2020-11-21 23:10

Java requires that if you call this() or super() in a constructor, it must be the first statement. Why?

For example:

public class MyClass {
    publi         


        
21条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 23:45

    I am fairly sure (those familiar with the Java Specification chime in) that it is to prevent you from (a) being allowed to use a partially-constructed object, and (b), forcing the parent class's constructor to construct on a "fresh" object.

    Some examples of a "bad" thing would be:

    class Thing
    {
        final int x;
        Thing(int x) { this.x = x; }
    }
    
    class Bad1 extends Thing
    {
        final int z;
        Bad1(int x, int y)
        {
            this.z = this.x + this.y; // WHOOPS! x hasn't been set yet
            super(x);
        }        
    }
    
    class Bad2 extends Thing
    {
        final int y;
        Bad2(int x, int y)
        {
            this.x = 33;
            this.y = y; 
            super(x); // WHOOPS! x is supposed to be final
        }        
    }
    

提交回复
热议问题