类的主动引用和被动引用

类的主动引用

  • 虚拟机启动时,main方法所在类。
  • new一个对象。
  • 调用类变量(final常量除外)和静态方法(可以是final方法)
  • 反射调用
  • 初始化一个类,如果其父类还没有别初始化,则会先初始化它的父类

类的被动引用(不会发生类的初始化)

  • 当访问一个静态域时,只要真正声明这个域的类才会被初始化。当通过子类引用父类的静态变量,不会导致子类初始化
  • 通过数组定义类引用,不会出发类的初始化。
  • 通过static final常量不会出发类的初始化【常量在链接阶段就存入调用类的常量池中了】
public class ZhuDongLoadAndBeidongLoad {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        System.out.println("【main方法被加载】");
        beidongLoad();
    }

    /**
     * 被动加载
     */
    public static void beidongLoad(){
        //当访问一个静态域时,只有真正声明这个域的类才被初始化。子类引用父类的静态变量或者静态方法,不会导致子类的初始化。
//        System.out.println(Son.father_static_field);//【main方法被加载 父类被加载 2】
//        Son.father_static_method();//【main方法被加载 父类被加载 2】

        //2通过数组定义类引用不会触发类初始化【main方法被加载】
//        Son[] sons = new Son[10];

        //3引用常量不会触发类初始化【main方法被加载】
        int m1 = Son.SON_STATIC_FINAL;
    }

    /**
     * 主动加载
     */
    public static void zhudongLoad() throws IllegalAccessException, InstantiationException {
        //1、new方式主动加载 【main方法被加载  父类被加载   子类被加载】
//        Son son = new Son();

        //2、反射方式主动加载 【main方法被加载  父类被加载   子类被加载】
//        Class<Son> sonClass = Son.class;
//        sonClass.newInstance();

        //3-1、调用类变量(除了final常量)和类方法【main方法被加载  父类被加载   子类被加载】
//        int m = Son.son_static_field;
        //3-2、调用类变量(除了final常量)和类方法【main方法被加载  父类被加载   子类被加载】
//         Son.son_static_method();
        //3-3、调用类变量(除了final常量)和类方法【main方法被加载  父类被加载   子类被加载】
        Son.son_static_final_method();
    }
}

class Father {
    static int father_static_field = 2;

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

}

class Son extends Father {
    static {
        System.out.println("子类被加载");
        son_static_field = 300;
    }
    static int son_static_field = 100;
    static final int SON_STATIC_FINAL = 1;

    public static void son_static_method() {

    }

    public static final void son_static_final_method() {

    }
}

 

posted @ 2022-06-16 22:15  禁止摆烂  阅读(63)  评论(0)    收藏  举报