閱讀920 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Java中類成員初始化順序問題

我下麵舉的例子是在Thinking in Java中摘取的,講的比較透徹,這裏與大家一起分享。

package com.thinking.chapter4;

class Bowl {
	public Bowl(int i) {
		System.out.println(i + " from Bowl");
	}

	void f1(int marker) {
		System.out.println("f1( " + marker + " )");
	}
}

class Table {
	static Bowl bowl1 = new Bowl(1);
	public Table() {
		System.out.println(" from table");
		bowl2.f1(1);
	}

	void f2(int marker) {
		System.out.println("f2( " + marker + " )");
	}
	static Bowl bowl2 = new Bowl(2);

}
class Cupboard {
	Bowl bowl3 = new Bowl(3);
	static Bowl bowl4 = new Bowl(4);
	public Cupboard() {
		System.out.println("Cupboard()");
		bowl4.f1(2);
	}
	void f3(int marker) {
		System.out.println("f3( " + marker + " )");
	}
	static Bowl bowl5 = new Bowl(5);
}
public class Init {
	static Table table = new Table();
	static Cupboard cupboard = new Cupboard();
	public static void main(String[] args) {
		System.out.println("create1 new Cupboard in main");
		new Cupboard();
		System.out.println("create2 new Cupboard in main");
		new Cupboard();
		
		table.f2(1);
		cupboard.f3(1);
	}
	
}
這是其輸出的結果。
1 from Bowl
2 from Bowl
 from table
f1( 1 )
4 from Bowl
5 from Bowl
3 from Bowl
Cupboard()
f1( 2 )
create1 new Cupboard in main
3 from Bowl
Cupboard()
f1( 2 )
create2 new Cupboard in main
3 from Bowl
Cupboard()
f1( 2 )
f2( 1 )
f3( 1 )
總結:

1.一個類成員中的屬性,分為static的和non-static的,對static的屬性該類的所有對象共有一份,non-static的屬性每個對象有一份。

2.如果在聲明類屬性時直接初始化,那麼這個初始化是先於構造函數執行的,其實還有一份默認初始化。

這一點比較容易讓大家忽略。舉個栗子:

class Student {
	int age = 18;
	Student() {
		age = 19;
	}
	
}
對於這個Student類,如果我們在一個main方法中new了一個Student類的對象,那麼age屬性的初始化過程時這樣的:

(1)首先,由於age是int類型,所以age被默認初始化為0

(2)然後,由於我們有顯式賦於值18,所以age的值又變為了18

(3)最後,由於我們的構造函數中又對age進行了初始化,所以最後age變為了19

我這裏舉的是例子中屬性類型是int,對於其他類型一樣適用,Object對象默認初始化為null。

3.在創建某對象時,如果該對象中既有static屬性又有non-static屬性,而且他們都在聲明時被初始化,那麼程序將先初始化static屬性,然後初始化non-static屬性。

最後更新:2017-04-03 20:19:53

  上一篇:go javascript 取整
  下一篇:go jQueryDom——Select、Option