声明为static的变量实质上就是全局变量。当声明一个对象时,并不产生static变量的拷贝,而是该类所有的实例变量共用同一个static变量。声明为static的方法有以下几条限制:
◆它们仅能调用其他的static 方法。
◆它们只能访问static数据。
◆它们不能以任何方式引用this 或super
但非static 方法可以访问static 成员
e.g.
public class StaticTest {
private static int count = 0;
private final int finalCount = count++;
public StaticTest(){
}
public int getFianlCount(){
return finalCount;
}
//每生成一个对象,finalCount就自加1
static StaticTest test1 = new StaticTest();
static StaticTest test2 = new StaticTest();
static StaticTest test3 = new StaticTest();
static StaticTest test4 = new StaticTest();
public static void main(String[] args) {
// TODO Auto-generated method stub
StaticTest test = new StaticTest();
System.out.println("finalCount is " + test.getFianlCount());
}
}