java 中 Cannot make a static reference to the non-static 解決方案__java

來源:互聯網
上載者:User

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

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.