为什么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)
?
为什么这需要成为第一个声明?
只是为了保持语言的流畅吗?
我是初学者请使用简单的术语:)