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)
打印0 (this.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(); } }
我希望有所帮助。
- 未在POM内部distributionManagement元素或-DaltDep loymentRepository = id :: layout :: url参数中指定存储库元素
- Duke快速重复数据删除:java.lang.UnsupportedOperationException:操作尚不支持?
- Java 8 – 构造函数参考 – 类型Select不定义此处适用的Select(DataObj)“
- 使用apache-commons-net TelnetClient发送终端命令时如何禁用echo
- 我怎么能用Hibernate的“无法解析配置”错误?
- Java jdesktop FrameView的windowClosing事件?
- 无法读取JSF组件上的ID
- 使用modyfing String迭代List
- 结合重叠日期范围 – Java