A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

代码如下:
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();
这两句最先执行的.

评分

参与人数 1技术分 +1 收起 理由
zzkang0206 + 1

查看全部评分

2 个回复

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

评分

参与人数 1技术分 +1 收起 理由
zzkang0206 + 1

查看全部评分

回复 使用道具 举报
程序加载类的时候,会先加载类的静态块,当你运行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
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马