【发布时间】:2013-12-10 11:40:31
【问题描述】:
如果我将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")之后,则不是第一条指令,而是第二条指令。 -
@OldProgrammer 我已经看到了那些答案,但仍然无法理解这就是我再次在这里问它的原因。再次询问是否违法?
-
因为这就是语言开发人员设计它的方式。这也是有道理的。这可以确保在执行派生类的构造函数中的任何其他语句之前,父类的任何属性/行为都处于正确的状态。
-
你不应该再问同样的问题,除非新问题明显不同。
标签: java constructor this