在开发中, 知道 Java 类的初始化顺序才能让我们更加清楚地掌握程序的执行流程. 先把结论贴出来, Java 里, 从图里的 1~6, 分别按顺序执行.
以下为代码验证阶段, 一共三个类: 基类 (Base), 子类(Sub) 和工具类(Log, 输出日志).
- package com.kobe.practice.order;
- public class Sub extends Base {
- public static void main(String[] args) {
- Sub sub = new Sub();
- }
- static {
- System.out.println("Sub static block 1");
- }
- private static String staticValue = Log.printLog("Sub static Fields");
- static {
- System.out.println("Sub static block 2");
- }
- {
- System.out.println("Sub normal block 1");
- }
- private String value = Log.printLog("Sub normal Fields");
- {
- System.out.println("Sub normal block 2");
- }
- public Sub() {
- System.out.println("Sub constructor");
- }
- }
- class Base {
- static {
- System.out.println("Base static block 1");
- }
- private static String staticValue = Log.printLog("Base static Fields");
- static {
- System.out.println("Base static block 2");
- }
- {
- System.out.println("Base normal block 1");
- }
- private String value = Log.printLog("Base normal Fields");
- {
- System.out.println("Base normal block 2");
- }
- public Base() {
- System.out.println("Base constructor");
- }
- }
- class Log {
- public static String printLog(String msg) {
- System.out.println(msg);
- return null;
- }
- }
输出结果:
- Base static block 1
- Base static Fields
- Base static block 2
- Sub static block 1
- Sub static Fields
- Sub static block 2
- Base normal block 1
- Base normal Fields
- Base normal block 2
- Base constructor
- Sub normal block 1
- Sub normal Fields
- Sub normal block 2
- Sub constructor
从结果能看出, 基类的静态代码块, 基类的静态成员变量(优先级相同, 根据在代码中的出现顺序执行, 且只有在类的一次加载时执行) → 派生类静态代码块, 派生类静态成员字段优先级相同, 根据在代码中的出现顺序执行, 且只有在类的一次加载时执行) → 基类普通代码块, 基类普通成员字段(优先级相同, 根据在代码中的出现顺序执行) → 基类的构造函数 → 派生类普通代码块, 派生类普通成员字段(优先级相同, 根据在代码中的出现顺序执行) → 派生类构造函数.
毫无疑问, Java 类的执行顺序十分重要, 谨记于心.
来源: https://www.cnblogs.com/kobelieve/p/10424409.html