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

一个静态变量初始化的顺序问题:
代码如下:
class Go {
static String s1 = "run";
static String s2, s3;
static {
s2 = "drive car";
s3 = "fly plane";
System.out.println("s2 & s3 initialized");
}
static void how() {
System.out.println(s1 + " or " + s2 + " or " + s3);
}
Go() { System.out.println("Go()"); }
}

public class ExplicitStatic {
public static void main(String[] args) {
System.out.println("Inside main()");
Go.how();
System.out.println("Go.s1: " + Go.s1);
}
static Go g1 = new Go();
static Go g2 = new Go();
}
运行结果:
s2 & s3 initialized
Go()
Go()
Inside main()
run or drive car or fly plane
Go.s1: run

想请问大侠们, 为什么s2&s3 initialized 这句会率先执行?
我以为会是static Go g1 = new Go();
static Go g2 = new Go();
这两句最先执行的.
------解决方案--------------------
程序加载类的时候,会先加载类的静态块,当你运行main方法时,首先会加载ExplicitStatic类,加载类的静态块,static Go g1 = new Go();static Go g2 = new Go(); 同样g1被new出来后,也会首先加载Go的静态块
static String s1 = "run";
static String s2, s3;
static {
s2 = "drive car";
s3 = "fly plane";
System.out.println("s2 & s3 initialized");
}
然后才是构造方法
Go() {
System.out.println("Go()");
}
当这些都加载完成后,开始执行main方法.所以 输出的结果是
s2 & s3 initialized
Go()
Go()
Inside main()
run or drive car or fly plane
Go.s1: run

PS.多了解一下加载机制 
<a>http://www.cnblogs.com/alexlo/archive/2013/03/05/2944573.html</a>