Behavior of static blocks with inheritance

后端 未结 5 834
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 20:13

I am trying to use static blocks like this:

I have a base class called Base.java

public class Base {

    static public int myVar;

}
         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 20:52

    Static initializer-blocks aren't run until the class is initialized. See Java Language Specification paragraphs 8.7 (Static initializers) and 12.4.1 (When initialization occurs):

    A static initializer declared in a class is executed when the class is initialized (§12.4.2). Together with any field initializers for class variables (§8.3.2), static initializers may be used to initialize the class variables of the class.

    Here's a similar example straight out of JLS 12.4.1:

    class Super {
      static int taxi = 1729;
    }
    class Sub extends Super {
      static { System.out.print("Sub "); }
    }
    class Test {
      public static void main(String[] args) {
        System.out.println(Sub.taxi);
      }
    }
    

    This program prints only:

    1729
    

    because the class Sub is never initialized; the reference to Sub.taxi is a reference to a field actually declared in class Super and does not trigger initialization of the class Sub.

提交回复
热议问题