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

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

    The reason is quite simple: for JVM not to do extra work prematurely (Java is lazy in its nature).

    Whether you write Super.staticMethod() or Sub.staticMethod(), the same implementation is called. And this parent's implementation typically does not depend on subclasses. Static methods of Super are not supposed to access members of Sub, so what's the point in initializing Sub then?

    Your example seems to be artificial and not well-designed.

    Making subclass rewrite static fields of superclass does not sound like a good idea. In this case an outcome of Super's methods will depend on which class is touched first. This also makes hard to have multiple children of Super with their own behavior. To cut it short, static members are not for polymorphism - that's what OOP principles say.

提交回复
热议问题