2016-08-15 4 views
-4

Почему выход «021»? Почему есть «0» и «1» (так как «i» получает «2», почему он меняется на «1»)?java constructor: 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(); 
    } 
} 

Я надеюсь, что поможет.