java构造函数:this(。)
问题描述:
为什么输出是“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();
}}
答
C()
呼叫C(1)
它调用C(1,1)
-
C(1,1)
打印(的this.i
默认值),并分配2(i+j
)至this.i
- 然后
C(1)
打印和受让人1至this.i
个
- 然后
C()
打印
答
我觉得这是更好地理解:
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();
}
}
我希望帮助。