In what order do static/instance initializer blocks in Java run?

前端 未结 8 1658
心在旅途
心在旅途 2020-11-22 17:01

Say a project contains several classes, each of which has a static initializer block. In what order do those blocks run? I know that within a class, such blocks are run in

8条回答
  •  长情又很酷
    2020-11-22 17:46

    class A {
      public A() { 
        // 2
      }
    }
    
    class B extends A{
      static char x = 'x'; // 0
      char y = 'y'; // 3
      public B() { 
        // 4
      }
    
      public static void main(String[] args) {
        new B(); // 1
      }
    }
    
    

    Numbers in the comment indicate the evaluation order, the smaller, the earlier.

    As the example showed,

    1. static variable
    2. main
    3. constructor of superclass
    4. instance variable
    5. constructor

提交回复
热议问题