標籤:
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方法的區別