Constructor call must be the first statement in a constructor错误的理解

先看一段代码:

public class Test2 {

public Test2(Object a){
System.out.println("a");
}
public Test2() {
super();
this(new Object());
test();
}
public void test() {

}
public static void main(String[] args) {

}
}

编译会报Constructor call must be the first statement in a constructor的错。这句话的意思是构造器必须放在构造函数的第一行。在构造方法Test2()使用了两个构造方法:

supper();

this(new Object());

这样就违反了Constructor call must be the first statement in a constructor这句话,因此编译报错。这样写也报错:

public Test2() {
test();
this(new Object());

}

原因一样,要遵循Constructor call must be the first statement in a constructor这句话。



你可能感兴趣的:(java)