過程如下:
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; } |
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! |