public class TestStatic {
static int i;
static{
System.out.println("Whether the first load...");
}
public TestStatic() {
// TODO Auto-generated constructor stub
System.out.println("non-arg...");
i=4;
}
public TestStatic(int j){
System.out.println("has-arg...");
i=j;
}
public static void main(String args[]){
TestStatic t1 = new TestStatic(10);
System.out.println(t1.i);
TestStatic t2 = new TestStatic();
//t2.i=8;
System.out.println(t1.i);
System.out.println(t2.i);
}
}
输出结果:
Whether the first load...
has-arg...
10
non-arg...
4
4
- static 方法块在类初始化之前执行 ,static变量 依赖实例,但不依赖具体实例(每次的赋值其他调用此变量的值随之改变。)