日期:2014-05-20  浏览次数:20622 次

【求助】下面这段代码输出结果是什么?为什么?
public class test1{
private int i = getValue();
private int j = 10;
int getValue(){
return j;
}
public static void main(String[] args){
System.out.print(new test1().i);
}
}
------解决方案--------------------
打印0
因为给i赋值的时候j还是默认值0。
如果j在i前面定义,就是10。

------解决方案--------------------
public class test2 {
    private int j = 10;
    private int i = getValue();
    int getValue(){
        return j;
    }
    public static void main(String[] args){
        System.out.print(new test2().i);
    }
}


执行结果为10
------解决方案--------------------
不管代码 多少,我们只看  main方法,  它打印的是 i这个成员变量,用的是系统  “默认”的构造方法,

public test2{
  i=0;
  j=0;
}
分别为  i,j初始化,不要被 getValue()方法诱惑,因为这里只用到了  new test(),它调用了构造方法,