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

前端 未结 7 1361
南方客
南方客 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:54

    The JLS is specifically allowing the JVM to avoid loading the Sub class, it's in the section quoted in the question:

    A reference to a static field (§8.3.1.1) causes initialization of only the class or interface that actually declares it, even though it might be referred to through the name of a subclass, a subinterface, or a class that implements an interface.

    The reason is to avoid having the JVM load classes unnecessarily. Initializing static variables is not an issue because they are not getting referenced anyway.

提交回复
热议问题