版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yz_cfm/article/details/89674861
问题引入:
eg1:
public class StaticTest {
// ①
private static StaticTest st = new StaticTest();
// ②
public static int count1;
// ③
public static int count2 = 0;
// ④
private StaticTest(){
count1++;
count2++;
}
// ⑤
public static StaticTest getInstance(){
return st;
}
public static void main(String[] args) {
// ⑥
StaticTest st = StaticTest.getInstance();
System.out.println("count1: " + count1);
System.out.println("count2: " + count2);
}
}
// output
count1: 1
count2: 0
结果分析:执行顺序:①-> ④(初始化 ② ③) -> ③( 因为有显式赋值,所以顺序执行之后并赋值 ) -> ⑥ -> ⑤;所以 count1 和 count2 最初初始化都为 0,执行完 StaticTest() 方法之后都变为 1,接着由于 ② 中没有显式赋值,此时依然为 1,而最后又执行到 ③ 时,由于有显式赋值,所以 count2 又被赋值为 0,所以最后的结果就变成了 1 和 0。
eg2:
public class StaticTest {
// ①
public static int count1;
// ②
public static int count2 = 0;
// ③
private static StaticTest st = new StaticTest();
// ④
private StaticTest(){
count1++;
count2++;
}
// ⑤
public static StaticTest getInstance(){
return st;
}
public static void main(String[] args) {
// ⑥
StaticTest st = StaticTest.getInstance();
System.out.println("count1: " + count1);
System.out.println("count2: " + count2);
}
}
// output
count1: 1
count2: 1
结果分析:执行顺序: ① -> ② -> ③ -> ④ -> ⑥ -> ⑤;所以最后结果为 1 和 1。
综上:static 修饰的变量、静态代码块等是在类加载时进行顺序执行的,也就是类执行之前完成的。