類變數和執行個體變數的區別
每次建立一個類的對象的時候,系統為它建立了類的每一個執行個體變數的副本。我們就可以從對象中訪問該執行個體變數。類變數或說靜態變數跟執行個體變數是不一樣的,不管為一個類建立了多少個對象,系統只為每個類變數分配一次儲存空間。系統為類變數分配的記憶體是在執行main方法時馬克-to-win, 就是在程式最最開始的時候(見下面StaticDemo的例子)。所有的對象共用了類變數。可以通過對象或者通過類本身來訪問類變數。Static fieldsA field define as static, means there is only one such field shared by all objectsInstance fieldsA field define without static, means each object has its own copy of fields順便提一句:通常用下面的形式,定義類的常量。(類或執行個體都可以訪問)static final double PI=3.14159;靜態方法(方法前冠以static)和執行個體方法(前面未冠以static)的區別調用靜態方法或說類方法時,可以使用類名做首碼,也可以使用某一個具體的對象名;通常使用類名。非static的方法是屬於某個對象的方法,而static的方法是屬於整個類的,不被任何一個對象單獨擁有;由於static方法是屬於整個類的,所以它不能操縱和處理屬於某個對象的成員變數,而只能處理屬於整個類的成員變數,也即,static方法只能處理static域或靜態方法。執行個體方法可以訪問執行個體域, 靜態域或靜態方法, 記住都行。聲明為static的方法有以下幾條限制: 1.它們僅能調用其他的static方法。2.它們只能訪問static資料。3.它們不能以任何方式引用this或super(關鍵 字super與繼承有關,在下一章中描述)。 static method Have No this ReferenceAll instance methods have a hidden parameter—thisSo,Static method can’t access instance methods and fields; it can only invoke other static class members.It can access class members only. instance can use static method.Instance methods:If a method is declared without the static modifier keyword, that method is known as an instance method. Instance methods are associated with objects – not classes.It can access either instance or class members. class StaticExa {static int a = 4;static int b = 9;static void call() {System.out.println("a = " + a);//靜態方法可以訪問靜態屬性}}public class Test {static int c = 43;public static void main(String args[]) {/*剛運行到這一步時,debug觀察,StaticExa.a的值就等於42,Test.c的值就等於43,說明系統在我們的程式一開始時,就會給所有的類變數賦值。如果是對象參考, 就是null,見photoshop的例子*/ System.out.println("開始觀察StaticExa.a和Test.c");