什么时候会发生类初始化:
1)new的时候
2)使用反射的时候
3)当初始化一个类,如果其父类没有被初始化,则先会初始化它的父类
测试:
1 package reflection;
2
3
4 import org.w3c.dom.ls.LSOutput;
5
6 import java.nio.file.FileSystemAlreadyExistsException;
7
8 // 测试类声明时候会初始化
9 public class Test06 {
10 static {
11 System.out.println("Main类被加载");
12 }
13 public static void main(String[] args) {
14 Son son = new Son();
15 }
16
17 }
18
19 class Father {
20 static int b = 2;
21 static {
22 System.out.println("父类被加载");
23 }
24 }
25
26 class Son extends Father {
27 static {
28 System.out.println("子类被加载");
29 m = 300;
30 }
31
32 static int m = 100;
33 static final int M = 1;
34
结果:
Main类被加载
父类被加载
子类被加载
1
结果:
Main类被加载
父类被加载
子类被加载
不会发生类初始化情况:
1)子类去调用父类的静态变量,不会导致子类初始化
1
结果:
Main类被加载
父类被加载
2
2)通过数组定义类引用,不会触发此类的初始化
1 Son[] sons = new
结果:
Main类被加载
3)引用常量不会触发此类的初始化(常量在链接阶段就存入调用类的常量池中了)
1