Java类加载顺序

父类: 

public class Father {

    int age = f1();

    int f1() {
        System.out.println("Father成员变量加载");
        return 4;
    }

    static int id = f2();

    static int f2() {
        System.out.println("Father静态成员变量加载");
        return 6;
    }

    public Father() {
        System.out.println("Father构造函数加载");
    }

    {
        System.out.println("Father方法块加载");
    }

    static {
        System.out.println("Father静态方法块加载");
    }

}

子类:

public class Child extends Father {

    int age = f3();

    int f3() {
        System.out.println("Child成员变量加载");
        return 4;
    }

    static int id = f4();

    static int f4() {
        System.out.println("Child静态成员变量加载");
        return 6;
    }

    public Child() {
        System.out.println("Child构造函数加载");
    }

    {
        System.out.println("Child方法块加载");
    }

    static {
        System.out.println("Child静态方法块加载");
    }

    // 执行Child的静态方法,会将A的静态成员变量加载,静态方法块加载,B的静态成员变量加载,静态方法块加载,然后执行B的静态方法。
    public static void executeStaticMethod() {
        System.out.println("Child静态方法☆☆☆执行☆☆☆");
    }
}

Main

public class Main {
    public static void main(String[] args) {
        Child.executeStaticMethod();
        System.out.println("==========Child的静态方法已经执行==========");
        Child b = new Child();
        System.out.println("==========第一个Child已实例化完成==========");
        Child b1 = new Child();
        System.out.println("==========第二个Child已实例化完成==========");
    }
}

 

实例化子类时的顺序:

父类静态成员变量
父类静态方法块
子类静态成员变量加载
子类静态方法块加载
父类成员变量加载
父类方法块加载
父类构造函数加载
子类成员变量加载
子类方法块加载
子类构造函数加载

 

调用子类的静态方法时的顺序:

Father静态成员变量加载
Father静态方法块加载
Child静态成员变量加载
Child静态方法块加载
Child静态方法☆☆☆执行☆☆☆

先调用子类静态方法再实例化子类

Father静态成员变量加载
Father静态方法块加载
Child静态成员变量加载
Child静态方法块加载
Child静态方法☆☆☆执行☆☆☆
==========Child的静态方法已经执行==========
Father成员变量加载
Father方法块加载
Father构造函数加载
Child成员变量加载
Child方法块加载
Child构造函数加载

 

先调用子类静态方法再多次实例化子类

 

Father静态成员变量加载
Father静态方法块加载
Child静态成员变量加载
Child静态方法块加载
Child静态方法☆☆☆执行☆☆☆
==========Child的静态方法已经执行==========
Father成员变量加载
Father方法块加载
Father构造函数加载
Child成员变量加载
Child方法块加载
Child构造函数加载
==========第一个Child已实例化完成==========
Father成员变量加载
Father方法块加载
Father构造函数加载
Child成员变量加载
Child方法块加载
Child构造函数加载
==========第二个Child已实例化完成==========

源码地址:https://github.com/yangpengjuJAVA666/study.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值