1. 程式人生 > >java 中的 Cannot make a static reference to the non-static method

java 中的 Cannot make a static reference to the non-static method


原文: https://blog.csdn.net/q610376681/article/details/49359819

 

今天敲程式碼的時候遇到了這個問題,大體這個問題可以簡化成這樣;

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);
    }
}