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

前端 未结 7 1346
南方客
南方客 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 14:07

    Be careful in your title, static fields and methods are NOT inherited. This means that when you comment staticMethod() in Sub , Sub.staticMethod() actually calls Super.staticMethod() then Sub static initializer is not executed.

    However, the question is more interesting than I thought at the first sight : in my point of view, this shouldn't compile without a warning, just like when one calls a static method on an instance of the class.

    EDIT: As @GeroldBroser pointed it, the first statement of this answer is wrong. Static methods are inherited as well but never overriden, simply hidden. I'm leaving the answer as is for history.

提交回复
热议问题