十、分析类初始化

狂神说Java:https://www.bilibili.com/video/BV1p4411P7V3

1、什么时候会发生类初始化

  • 类的主动引用(一定会发生类的初始化)
    • 当虚拟机启动时,先初始化main方法所在的类
    • new一个类的对象
    • 调用类的静态成员(除了final常量)和静态方法
    • 使用java.lang.reflect包的方法对类进行反射调用
    • 当初始化一个类,如果其父类没有被初始化,则会先初始化它的父类
  • 类的被动引用(不会发生类的初始化)、
    • 当访问一个静态域时,只有真正声明这个域的类才会被初始化。如:当通过子类引用父类的静态变量,不会导致子类初始化。
    • 通过数组定义类引用,不会触发此类的初始化。
    • 引用常量不会触发此类的初始化(常量在链接阶段就存入类的常量池中了)

2、主动引用测试

new一个类

package com.hejin.reflection;

/**
 * @Description 类什么时候会初始化
 * @Author Administrator
 * @Date 2020/12/2 9:51
 */
public class Test06 {

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

    public static void main(String[] args) throws ClassNotFoundException {
        /**
         * 1、new
         */
        Son son = new Son();
    }

}

class Father{

    static int b = 2;

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

}

class Son extends Father {
    static {
        System.out.println("子类被加载");
        m = 300;
    }

    static int m = 100;
    static final int M = 1;
}

结果

Main类被加载
父类被加载
子类被加载

Process finished with exit code 0

反射

package com.hejin.reflection;

/**
 * @Description 类什么时候会初始化
 * @Author Administrator
 * @Date 2020/12/2 9:51
 */
public class Test06 {

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

    public static void main(String[] args) throws ClassNotFoundException {
        /**
         * 2、反射
         */
        Class.forName("com.hejin.reflection.Son");

    }

}

class Father{

    static int b = 2;

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

}

class Son extends Father {
    static {
        System.out.println("子类被加载");
        m = 300;
    }

    static int m = 100;
    static final int M = 1;
}

结果

Main类被加载
父类被加载
子类被加载

Process finished with exit code 0

3、被动引用测试

子类引用父类的静态变量

// 子类引用父类的静态变量
System.out.println(Son.b);

结果

Main类被加载
父类被加载
2

Process finished with exit code 0

数组定义类引用

// 数组定义类引用
Son[] array = new Son[5];

结果

Main类被加载

Process finished with exit code 0

引用常量

// 引用常量
System.out.println(Son.M);

结果

Main类被加载
1

Process finished with exit code 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值