今天敲代碼的時候遇到了這個問題,大體這個問題可以簡化成這樣;
public class Test1 { public String get() { return "123"; } public static void main(String[] args) { String string =get(); }}
顯示
Cannot make a static reference to the non-static method get() from the type Test1
好吧,我決定改成這樣
public class Test1 { public String get() { return "123"; } public static void main(String[] args) { static String string =get(); }}
可是還是錯的。。。。
翻了一下java書才知道
1.java中 靜態方法不可以直接調用非靜態方法和成員,也不能使用this關鍵字(這就是這個問題的原因,我用靜態main方法調用了非靜態的get方法)。
原因解釋:類中靜態方法或者屬性,本質上來講並不是該類的成員,在java虛擬機器裝在類的時候,這些靜態東西已經有了對象,它只是在這個類中”寄居”,不需要通過類的構造器(建構函式)類實現執行個體化;而非靜態屬性或者方法,在類的裝載是並沒有存在,需在執行了該類的建構函式後才可依賴該類的執行個體對象存在。所以在靜態方法中調用非靜態方法時,編譯器會報錯(Cannot make a static reference to the non-static method func() from the type A)。 java中不能將方法體內的局部變數聲明為static main()函數是靜態,沒有傳回值,形參為數組。 非靜態成員的可以隨便調用靜態成員
原來靜態這麼反人類,那要this的幹什麼呢。
大概就是為了使多個類共用一個資料。
大概修改了一下,將函數變為static,將變數聲明為全域靜態
方法一:
public class Test1 { static String string; public static String get() { return "123"; } public static void main(String[] args) { string =get(); System.out.print(string); }}
方法二
public class Test1 { public String get() { return "123"; } public static void main(String[] args) { Test1 c = new Test1(); String string = c.get(); System.out.print(string); }}