java构造函数:这个(.)

java构造函数:这个(.),java,constructor,Java,Constructor,为什么输出为“021”?为什么会有“0”和“1”(既然“i”得到“2”,为什么会变为“1”) C()调用C(1)哪个调用C(1,1) C(1,1)打印0(this.i的默认值)并将2(i+j)赋值给this.i 然后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(

为什么输出为“021”?为什么会有“0”和“1”(既然“i”得到“2”,为什么会变为“1”)

C()
调用
C(1)
哪个调用
C(1,1)

  • C(1,1)
    打印0
    this.i
    的默认值)并将2(
    i+j
    )赋值给
    this.i
  • 然后
    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();
          }
      }
      
      我希望这能有所帮助

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