Why is a subclass' static initializer not invoked when a static method declared in its superclass is invoked on the subclass?

前端 未结 7 1348
南方客
南方客 2021-02-02 13:16

Given the following classes:

public abstract class Super {
    protected static Object staticVar;

    protected static void staticMethod() {
        System.out.p         


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-02 13:53

    for some reason jvm think that static block is no good, and its not executed

    I believe, it is because you are not using any methods for subclass, so jvm sees no reason to "init" the class itself, the method call is statically bound to parent at compile time - there is late binding for static methods

    http://ideone.com/pUyVj4

    static {
        System.out.println("init");
        staticVar = new Object();
    }
    

    Add some other method, and call it before the sub

    Sub.someOtherMethod();
    new UsersClass().method();
    

    or do explicit Class.forName("Sub");

    Class.forName("Sub");
    new UsersClass().method();
    

提交回复
热议问题