2016-08-15 111 views
-4

为什么输出是“021”?为什么有“0”和“1”(因为“我”得到“2”为什么变成“1”)?java构造函数:this(。)

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(); 
}} 

回答

7

C()呼叫C(1)它调用C(1,1)

  • C(1,1)打印(的this.i默认值),并分配2(i+j)至this.i
  • 然后C(1)打印和受让人1至this.i
  • 然后C()打印
2

我觉得这是更好地理解:

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,可获取这些方法的顺序();

1

下面的代码注释,现在你就会明白你的问题,

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(); 
    } 
} 

我希望帮助。