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 classTreeNode {2 intval;3 TreeNode left;4 TreeNode right;5 TreeNode(int num){val =num;}6 }
第二种,在当前类文件里建一个内部类。代码如下。
1 public classtest {2
3 public static classTreeNode {4 intval;5 TreeNode left;6 TreeNode right;7 TreeNode(int num){val =num;}8 }9
10 public static voidmain(String[] args) {11 //TODO Auto-generated method stub
12 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).