https://s3-us-west-2.amazonaws.com/secure.notion-static.com/776865ff-2ae7-4819-9172-97048fa5f8d3/IMG_0227.jpg

代码

package top.ltyzqhh.Reflection;

//测试类什么时候会被初始化
public class Test05 {

    static {
        System.out.println("main类被加载");
    }

    public static void main(String[] args) throws ClassNotFoundException {
        //1.主动引用
       // Son son =new Son();

        //2.反射也会产生主动引用
        //Class.forName("top.ltyzqhh.Reflection.Son");

        //3.不会产生类的引用的方法
        System.out.println(Son.b);

        Son[] array = new Son[5];

        System.out.println(Son.M);

    }
}

class Father{

    static  int b=2;

    static {
        System.out.println("父类被加载");
    }
}

class Son extends Father{

    static {
        System.out.println("子类被加载");
        m=300;
    }
    static int m=300;
    static final int M = 1;
}

1、2的结果

3的结果

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/f9ccb82d-deeb-44cd-b8ef-56eef9c6c443/Snipaste_2021-05-07_19-02-11.png

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/09eb9558-eebd-45c4-ad64-d62bf1d08a4b/Snipaste_2021-05-07_19-04-25.png

思考:常量其实在链接阶段就已经存入常量池中