为什么this()
需要在构造函数链的第一个语句中?为什么具有不同参数的多个`this()`在父构造函数中不起作用?
为什么多个this()
具有不同的参数不能在最终的构造函数中工作?
package thislatest;
public class ThisLatest {
public static void main(String[] args) {
A a1= new A(10,20,30);
a1.display();
}
}
class A
{
int x,b;
static int c;
A(){ System.out.println("constructor chaining1");}
A(int y)
{ //this();
System.out.println("constructor chaining2");
b=y;
}
A(int x,int y)
{
// this(x);
System.out.println("constructor chaining3");
x=x;
x=y;
}
A(int x,int y,int c)
{ this();
this(y);
this(x,y);
x=x; //self reference initialised by previous constructor
b=y; //no need of this keyword since name is different
this.c=c; //current instance variable or A.c=c will also work
}
void display()
{
System.out.println(x+b); //wrong result due to self reference
System.out.println(c+b); //correct reference
}
}
我为什么不能使用多个this()
在构造函数中A(int x,int y,int c)
?
为什么这需要成为第一个陈述?
只是为了保持语言流畅吗?
我是初学者,请用简单的术语:)
很好读这个http://stackoverflow.com/questions/1168345/why-does-this-and-super-have-to-be-the-first-statement-in-a-constructor?rq=1 –
我在阅读相同类型的问题之前阅读了stackoverflow答案。我不明白这些答案 – ekaf
你可以用私人初始化方法做到这一点,没有副作用。但是如果你要求构造函数,你应该考虑在最后的领域,如果你用许多构造函数初始化这个最终字段,最终字段可以被初始化一些次,这是一个问题。 –