我不理解为什么在构造函数中将 this(1);
移到最后一行时,下面的代码会显示错误信息 Constructor call must be the first statement in a constructor
。
package learn.basic.corejava;
public class A {
int x,y;
A()
{
// this(1);// ->> works fine if written here
System.out.println("1");
this(1); //Error: Constructor call must be the first statement in a constructor
}
A(int a)
{
System.out.println("2");
}
public static void main(String[] args) {
A obj1=new A(2);
}
}
我在StackOverflow上检查了很多关于这个话题的答案,但我仍然无法理解其中的原因。请用一些简单的例子和解释帮助我澄清这个错误。
this(...)
的调用必须是第一条指令。如果它在System.out.println("1")
之后出现,则不是第一条指令,而是第二条指令。 - JB Nizet