构造函数调用必须是构造函数中的第一条语句
问题描述:
我不明白为什么下面的代码显示错误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上检查了很多关于这个主题的答案,但我仍然无法理解这个原因。请用一些简单的例子和解释来帮助我澄清这个错误。
答
如你所知,这个工程:
A() {
this(1);
System.out.println("1");
}
为什么?因为它是Java语言规范中的一条语言规则:对同一类中的另一个构造函数(this(...)
部分)或超类中的构造函数(使用super(...)
)的调用必须放在第一行。这是一种确保在初始化当前对象之前初始化父对象的状态的方法。
欲了解更多信息,请看这post,它详细解释情况。
答
的这个错误告诉你问题
A()
{
System.out.println("1");
this(1); //Error: Constructor call must be the first statement in a constructor
}
即必须调用原因是在回答构造第一
A()
{
this(1);
System.out.println("1");
}
这也适用于调用超级
class B extends A
{
B()
{
super();
System.out.println("1");
}
}
+0
感谢您的回答。我阅读这些(http://stackoverflow.com/questions/1168345/why-does-this-and-super-have-to-be-the-first-statement-in-a-constructor)的答案,但仍然无法理解这就是为什么我在这里问这个问题。 – beginner
原因是“构造函数调用必须是构造函数中的第一条语句”。因此在构造函数中,对this(...)'的调用必须是第一条指令。如果它出现在System.out.println(“1”)之后,它不是第一条指令,而是第二条指令。 –
@OldProgrammer我已经看到了这些答案,但仍然无法理解,这就是为什么我在这里再次问它。这又是否违法? – beginner
因为这是该语言的开发人员设计它的方式。这也是有道理的。这确保了在派生类的构造函数中执行任何其他语句之前,父类的任何属性/行为都处于适当状态。 – OldProgrammer