黑马程序员技术交流社区

标题: 一个静态变量初始化的顺序问题 [打印本页]

作者: 我爱的是你爱我_    时间: 2014-3-18 16:18
标题: 一个静态变量初始化的顺序问题
代码如下:
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();
这两句最先执行的.
作者: 我爱的是你爱我_    时间: 2014-3-18 16:27
程序加载类的时候,会先加载类的静态块,当你运行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

作者: zhxu188    时间: 2014-3-18 22:22
程序在运行时,记住先加载类中的静态代码块,然后加载构造代码块,最后加载构造函数,所有的程序都是按照这个顺序执行的。楼上大神已经把程序执行的过程说明白了,我就不再一一重复了,只要告诉楼主,先加载类中的静态代码块,然后加载构造代码块,最后加载构造函数,记住喽哦




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2