我不明白为什么下面的代码显示错误Constructor call must be the first statement in a constructor
如果我将this(1);
移到构造函数的最后一行。构造函数调用必须是构造函数中的第一条语句
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”)之后,它不是第一条指令,而是第二条指令。 –
@OldProgrammer我已经看到了这些答案,但仍然无法理解,这就是为什么我在这里再次问它。这又是否违法? – beginner
因为这是该语言的开发人员设计它的方式。这也是有道理的。这确保了在派生类的构造函数中执行任何其他语句之前,父类的任何属性/行为都处于适当状态。 – OldProgrammer