java程序初始化過程詳解

 過程如下:

  1.在類的聲明裏查看有無靜態元素(static element, 我姑且這麼叫吧),比如: 

 static int x = 1,
  {
  //block
  float sss = 333.3; String str = "hello";
  }
  或者 比如
  static {
  //(static block),
  int x = 2;
  double y = 33.3;
  }
  如果有static element則首先執行其中語句,但注意static element只執行一次,在第二次創建類的對象的時候,就不會去執行static element的語句.

  2.查看此類是否爲啓動運行類,若爲啓動運行類,則執行main()方法裏的語句對應語句

  3.若不是啓動運行類,則按代碼的排版先後順序繼續執行非static element的變量賦值以及代碼塊.

  4.最後執行構造方法,如果在被調用的構造方法裏面有this關鍵字(注意,如果你考慮要調用其他構造方法,則應該把this寫在最前面,不然會產生錯誤),則先調用相應構造方法主體,調用完之後再執行自己的剩下語句. 

 /** *//**
  *
  * @author livahu
  * Created on 2006年9月6日, 下午17:00
  */
  class FirstClass ...{
  FirstClass(int i) ...{
  System.out.println("FirstClass(" i ")");
  }
  void useMethod(int k) ...{
  System.out.println("useMethod(" k ")");
  }
  }
  class SecondClass ...{
  static FirstClass fc1 = new FirstClass(1);
  FirstClass fc3 = new FirstClass(3);
  static ...{
  FirstClass fc2 = new FirstClass(2);
  }
  ...{
  System.out.println("SecondClass's block, this block is not static block.");
  }
  SecondClass() ...{
  System.out.println("SecondClass()");
  }
  FirstClass fc4 = new FirstClass(4);
  }
  public class InitiationDemo ...{
  SecondClass sc1 = new SecondClass();
  ...{
  System.out.println("Hello Java World!");
  }
  public static void main(String[] args) ...{
  System.out.println("Inside main()");
  SecondClass.fc1.useMethod(100);
  InitiationDemo idObj = new InitiationDemo();
  }
  static SecondClass sc2 = new SecondClass();
  }

運行結果:  

FirstClass(1)
  FirstClass(2)
  FirstClass(3)
  SecondClass's block, this block is not static block.
  FirstClass(4)
  SecondClass()
  Inside main()
  useMethod(100)
  FirstClass(3)
  SecondClass's block, this block is not static block.
  FirstClass(4)
  SecondClass()
  Hello Java World!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章