public class staticTest
{
 private static String[] tests = null;//(1)

 private static staticTest instance = new staticTest();

 //private static String[] tests = null;//(2)
 private staticTest(){
  init();
 }

 private void init(){
  tests = new String[8];
  for (int i = 0; i < tests.length; i++){
   tests[i] = "test" + i;
  }
 }

 public void print(){
  for (int i = 0; i < tests.length; i++){
   System.out.println(tests[i]);// = "test"+i;
  }
 }

 public static staticTest getInstance(){
  return instance;
 }

 public static void main(String[] args) throws Exception{
  staticTest.getInstance().print();

 }
}


該類測試static關鍵字對類初始化影響,如果把位于(1)的代碼放到(2)的位置,則該類執行main方法時會報錯----空指針異常:
原因在哪里呢?
static 定義的成員變量是按定義的位置初始化的,盡管在staticTest的構造函數中tests 被初始化,但由于(2)語句定義的位置,有使得tests 的值為null.