Java 静态方法调用类初始化规则观察记录

1、基本介绍
  • 静态方法调用不会触发子类的初始化,只会触发声明该方法的类及其父类的初始化
2、观察记录
(1)测试 1
public class CommonStore {
    static {
        System.out.println("CommonStore static execute");
    }

    protected static int line;

    public static int getCount() {
        return line * 10;
    }
}
public class MyStore extends CommonStore {
    static {
        System.out.println("MyStore static execute");

        line = 10;
    }
}
System.out.println(MyStore.getCount());
# 输出结果

CommonStore static execute
0
  1. getCount 方法是在 CommonStore 中声明的静态方法

  2. JVM 只看声明类(CommonStore),不看调用时写的类名(MyStore)

  3. 所以只初始化 CommonStore,不会初始化 MyStore

  4. MyStore 的静态代码块没执行,line 保持默认值 0,getCount 方法返回 0

(2)测试 2
public class CommonStore {
    static {
        System.out.println("CommonStore static execute");
    }

    protected static int line;

    public static int getCount() {
        return line * 10;
    }
}
public class MyStore extends CommonStore {
    static {
        System.out.println("MyStore static execute");

        line = 10;
    }

    public static void init() {
        System.out.println("MyStore init execute");
    }
}
MyStore.init();
System.out.println(MyStore.getCount());
# 输出结果

CommonStore static execute
MyStore static execute
MyStore init execute
100
  1. MyStore 的 init 方法是 MyStore 的静态方法,JVM 初始化 MyStore

  2. 初始化子类前,先初始化父类,输出 CommonStore static execute

  3. 然后初始化 MyStore,输出 MyStore static execute,执行 line = 10

  4. init 方法执行,输出 MyStore init execute

  5. getCount 方法执行,返回 100

(3)测试 3
public class CommonStore {
    static {
        System.out.println("CommonStore static execute");
    }

    protected static int line;

    public static int getCount() {
        return line * 10;
    }
}
public class MyStore extends CommonStore {
    static {
        System.out.println("MyStore static execute");

        line = 10;
    }

    public static void init() {
        System.out.println("MyStore init execute");
    }
}
MyStore.init();
# 输出结果

CommonStore static execute
MyStore static execute
MyStore init execute

更多推荐