定义
存储在静态区的变量或者方法
用途
咱先来看一个例子:
public class staticTest extends stasticTestDemo {
int age;
int height;
String country;
}
......
public class stasticTestDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
staticTest p1=new staticTest();
staticTest p2=new staticTest();
p1.age=24;
p1.height=165;
p2.age=24;
p2.height=172;
p1.country="China";
p2.country="China";
}
}
我们可以从这个例子中看到,p1,p2中的country成员变量都是同一个值,如果说对于所有的stasticTest类的对象的country变量都是同样的,我们能不能用一种共享的变量来表示呢?
于是我们就可以使用static关键词,对该变量和方法设置成静态的,它们都会放到静态区中。也即是共享区,所有该类的对象都可以直接共用。
String country;
----->static String country;
咱们再来看一个例子:
public class staticTest extends stasticTestDemo {
int age;
int height;
static String country;
public static void showAge()
{
System.out.println("Age:"+Age);
}
}
结果报错,看一下
Cannot make a static reference to the non-static field age
这句话的大概意思就是age是非静态变量
也就是说,静态方法只能访问静态变量