Static means "global" or "static", which is used to modify member variables and member methods. member variables and member methods that are modified by static are independent of any object of the class. That is, it does not depend on class-specific instances and is shared by all instances of the class. Static methods can be called directly from the class name, and any instance can also be called. Therefore, the this and Super keywords cannot be used in a static method, and you cannot directly access the instance variables and instance methods of the owning class (that is, member variables and member methods without static), only the static member variables and member methods of the owning class.
Therefore, the Func_static method can access only NUM2 members in the following code, while the Func method accesses both Num1 and num2.
1 Public class Test {2private int NUM1 =1;3private static int num2 =2;4 5 Public static void func_static (int n) {6num2 =N;7 }8 9 Public void func (int n) {TenNUM1 =N; Onenum2 =N; A } -}
Related issues
Q1: The Main method in Java, why is it static (static)?
A: This way the JVM can invoke the main method of a class file directly without creating an instance.
Q2: How to implement a struct structure similar to C in Java. such as the node of the two-fork tree.
A: two methods.
First, create a separate class file Treenode.java. The code is as follows.
1 Public class TreeNode {2 int Val; 3 TreeNode left; 4 TreeNode right; 5 TreeNode (int num) {val = num;} 6 }
Second, an inner class is built in the current class file. The code is as follows.
1 Public classTest {2 3 Public Static classTreeNode {4 intVal;5 TreeNode left;6 TreeNode right;7TreeNode (intnum) {val =num;}8 }9 Ten Public Static voidMain (string[] args) { One //TODO auto-generated Method Stub ATreeNode node =NewTreeNode (1); - } -}
It is noteworthy here that we declared static when we built the inner class TreeNode. If it is not static, the 12th line of code will error: 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 was an instance of test).
Differences between the static and non-static methods of the Java learning Note