beg*_*ner 7 java constructor this
我不明白为什么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);
}
}
Run Code Online (Sandbox Code Playgroud)
我在StackOverflow上检查了很多关于这个主题的答案,但我仍然无法理解这个原因.请帮我用一些简单的例子和解释来说明这个错误.
如您所知,这有效:
A() {
this(1);
System.out.println("1");
}
Run Code Online (Sandbox Code Playgroud)
为什么?因为它是Java语言规范中存在的语言规则:对同一个类(this(...)部分)中的另一个构造函数或超类中的构造函数(using super(...))的调用 必须放在第一行.这是一种确保在初始化当前对象之前初始化父级状态的方法.
有关详细信息,请查看此文章,详细说明情况.