Java 中类的变量、代码块、构造方法加载的顺序

Java 面试 大约 2536 字

加载顺序

  1. 父类静态变量
  2. 父类静态代码块
  3. 子类静态变量
  4. 子类静态代码块
  5. 父类成员变量
  6. 父类代码块
  7. 父类构造方法
  8. 子类成员变量
  9. 子类代码块
  10. 子类构造方法

示例代码

public class Parent {

    public static final ParentStaticFiled PARENT_STATIC_FILED = new ParentStaticFiled();

    public ParentMemberFiled parentMemberFiled = new ParentMemberFiled();

    private String parentMemberVar;

    static {
        System.out.println(LocalDateTime.now() + " Parent static block#" + PARENT_STATIC_FILED);
    }

    {
        System.out.println(LocalDateTime.now() + " Parent non static block#" + parentMemberVar);
    }

    public Parent() {
        parentMemberVar = "pmv";
        System.out.println(LocalDateTime.now() + " Parent Constructor#" + parentMemberVar);
    }
}

public class ParentStaticFiled {

    public ParentStaticFiled() {

        System.out.println(LocalDateTime.now() + " Parent static field");

    }
}

public class ParentMemberFiled {

    public ParentMemberFiled() {

        System.out.println(LocalDateTime.now() + " Parent member field");

    }
}

public class Child extends Parent {

    public static final ChildStaticFiled CHILD_STATIC_FILED = new ChildStaticFiled();

    public String childMemberVar = "cmv";

    public ChildMemberFiled childMemberFiled = new ChildMemberFiled();

    static {
        System.out.println(LocalDateTime.now() + " Child static block#" + CHILD_STATIC_FILED);
    }

    {
        System.out.println(LocalDateTime.now() + " Child non static block#" + childMemberVar);
    }

    public Child() {
        System.out.println(LocalDateTime.now() + " Child constructor#" + childMemberVar);
    }

    public static void main(String[] args) {
        Child child = new Child();
    }

}

public class ChildStaticFiled {

    public ChildStaticFiled() {

        System.out.println(LocalDateTime.now() + " Child static field");

    }
}

public class ChildMemberFiled {

    public ChildMemberFiled() {

        System.out.println(LocalDateTime.now() + " Child member field");

    }
}

输出:

2021-04-19T19:58:34.549045300 Parent static field
2021-04-19T19:58:34.564671500 Parent static block#ParentStaticFiled@402f32ff
2021-04-19T19:58:34.595926100 Child static field
2021-04-19T19:58:34.595926100 Child static block#ChildStaticFiled@5ae9a829
2021-04-19T19:58:34.595926100 Parent member field
2021-04-19T19:58:34.595926100 Parent non static block#null
2021-04-19T19:58:34.595926100 Parent Constructor#pmv
2021-04-19T19:58:34.595926100 Child member field
2021-04-19T19:58:34.595926100 Child non static block#cmv
2021-04-19T19:58:34.595926100 Child constructor#cmv
阅读 406 · 发布于 2021-04-19

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批