我有如下場景 package com.example.test;執行順序,靜態塊
public class StaticTest {
public static final String STATIC_VAR="Static Var";
static{
System.out.println("Static Block Called....");
}
public static void init(){}
}
package com.example.test;
public class MainClass {
public static void main(String[] args) {
System.out.println("Test static initialization");
String staticvar =StaticTest.STATIC_VAR;
System.out.println("Referred static variable--> "+ staticvar);
System.out.println("Calling static method");
StaticTest.init();
System.out.println("Static method invoked");
}
}
我得到的輸出是
Test static initialization
Referred static variable--> Static Var
Calling static method
**Static Block Called....**
Static method invoked
和輸出我所期待的是
Test static initialization
**Static Block Called....**
Referred static variable--> Static Var
Calling static method
Static method invoked
我想,只要我指靜態變量靜態塊將得到執行。
有什麼解釋?
請參閱[Java靜態類初始化](http://stackoverflow.com/questions/3499214/java-static-class-initialization)和[靜態塊和靜態變量在一個類中執行的順序是什麼?](http ://stackoverflow.com/questions/12448465/in-what-order-are-static-blocks-and-static-variables-in-a-class-executed)。 –