java构造函数:this(。)

为什么输出为“021”? 为什么有“0”和“1”(因为“我”得到“2”为什么它变成“1”)?

public class C { protected int i; public C(int i){ this(i,i); System.out.print(this.i); this.i=i; } public C(int i, int j) { System.out.print(this.i); this.i=i+j; } public C(){ this(1); System.out.print(i); } public static void main(String[] args) { C c=new C(); }} 

C()调用C(1)调用C(1,1)

  • C(1,1)打印0this.i的默认值)并为this.i分配2( i+j
  • 然后C(1)打印2并将1分配给this.i
  • 然后C()打印1

我认为这对理解更好:

 public C(int i) { this(i, i); System.out.println("*"+this.i); this.i = i; } public C(int i, int j) { System.out.println("@"+this.i); this.i = i + j; } public C() { this(1); System.out.println("#"+i); } 

现在,您可以在调用C()时获取这些方法的序列;

在这里代码评论,你现在就能理解你的问题,

 public class C { protected int i; public C(int i) { this(i, i); // got to two parameter constructer and after the result print the next line System.out.print(" + second "+this.i); // print value of i which is come from C(int i, int j) = 2 this.i = i; // set the value of i to 1 } public C(int i, int j) { System.out.print("first "+this.i); // print the value of i (in this case 0 the default value) this.i = i + j; // set i to 2 } public C() { this(1); // got to one parameter constructer and after the result print the next line System.out.print(" + Third is "+i); // print value of i which is come from C(int i) = 1 } public static void main(String[] args) { C c = new C(); } } 

我希望有所帮助。