2016-08-15 113 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(); 
    } 
} 

我希望幫助。