代码来自thinking in java 3rd
想不通打印出来字符串的顺序
为什么先打印出Insect这个类中private static方法的字符串
然后打印Bettle类里面的private static 方法里的字符串
然后才执行main() 方法里的pringln 方法??
main()里的println语句在创建类的实例之前啊!!
import com.bruceeckel.simpletest.*;
class Insect
{
protected static Test monitor =new Test();
private int i=9;
protected int j;
Insect ()
{
System.out.println( "i= "+i+ ",j= "+j);
j=39;
}
private static int x1=print( "static Insect.x1 initialized ");
static int print(String s)
{
System.out.println(s);
return 47;
}
public class Beetle extends Insect
{
private int k=print( "Veetle.k intitialized ");
public Beetle()
{
System.out.println( "k= "+k);
System.out.println( "j= "+j);
}
private static int x2=print( "static Beetle.x2 initialized ");
public static void main(String[] args)
{
System.out.pringln( "Beetle constructor ");
Beetle b=new Beetle();
monitor.expect(new Beetle());
monitor.expect(new String[]{
"static Insect.x1 initialized ",
"static Beetle.x2 initialized ",
"Beetle constructor ",
"i=9,j=0 ",
"Beetle.k initialized ",
"k=47 ",
"j=39 ",
});
}
} ///:~
------解决方案--------------------
在载入Insect时,为了初始化静态变量int x1,要先调用print( "static Insect.x1 initialized ");取得返回值,完成初始化的