class Tag {Tag(int marker) {System.out.PRintln("Tag(" + marker + ")");}}class Card {Tag t1 = new Tag(1); // Before constructorCard() {// Indicate we're in the constructor:System.out.println("Card()");t3 = new Tag(33); // Re-initialize t3}Tag t2 = new Tag(2); // After constructorvoid f() {System.out.println("f()");}Tag t3 = new Tag(3); // At end}public class OrderOfInitialization {public static void main(String[] args) {Card t = new Card();t.f(); // Shows that construction is done}}初始化的順序是由變量在類內的定義順序決定的。即使變量定義大量遍布于方法定義的中間,那些變量仍會在調用任何方法之前得到初始化——甚至在構建器調用之前,就是先初始化成員變量,再構建器,最后是方法,所以上邊的代碼執行順序是
Tag(1)Tag(2)Tag(3)Card()Tag(33)f()
新聞熱點
疑難解答