【Java學習筆記】static方法和非static方法的區別

來源:互聯網
上載者:User

標籤:

static表示“全域”或者“靜態”的意思,用來修飾成員變數和成員方法。被static修飾的成員變數和成員方法獨立於該類的任何對象。也就是說,它不依賴類特定的執行個體,被類的所有執行個體共用。靜態方法可以直接通過類名調用,任何的執行個體也都可以調用。因此靜態方法中不能用this和super關鍵字,不能直接存取所屬類的執行個體變數和執行個體方法(就是不帶static的成員變數和成員成員方法),只能訪問所屬類的靜態成員變數和成員方法。

因此以下代碼中,func_static方法只能訪問num2成員,而func方法可以同時訪問num1和num2。

 1 public class test { 2     private int num1 = 1; 3     private static int num2 = 2; 4      5     public static void func_static(int n) { 6         num2 = n; 7     } 8      9     public void func(int n) {10         num1 = n;11         num2 = n;12     }13 }

 

相關問題

Q1:java中的main方法,為什麼是靜態(static)的?

A:這樣JVM可以直接調用某個類檔案的main方法,而不用建立一個執行個體。

 

Q2:java中如何?類似C中struct結構體。比如二叉樹的節點。

A:兩種方法。

第一種,單獨建立一個類檔案TreeNode.java。代碼如下。

1 public class TreeNode {2     int val;3     TreeNode left;4     TreeNode right;5     TreeNode(int num){val = num;}6 }

第二種,在當前類檔案裡建一個內部類。代碼如下。

 1 public class test { 2      3     public static class TreeNode { 4         int val; 5         TreeNode left; 6         TreeNode right; 7         TreeNode(int num){val = num;} 8     } 9     10     public static void main(String[] args) {11         // TODO Auto-generated method stub12         TreeNode node = new TreeNode(1);13     }14 }

這裡值得注意的是我們在建立內部類TreeNode時聲明了static。如果不是static,第12行代碼會報錯:No enclosing instance of type test is accessible. Must qualify the allocation with an enclosing instance of type test (e.g. x.new A() where x is an instance of test).

【Java學習筆記】static方法和非static方法的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.