1. normal method uses static field => fine
public class StaticFieldDemo {
public static int staticVar;
public int instanceVar;
/*
* test1 normal method uses static field
*/
public void NormalMethodincrementStaticField() {
++staticVar;
System.out.println("static field staticVar = " + staticVar);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//test1
StaticFieldDemo sfd1 = new StaticFieldDemo();
sfd1.NormalMethodincrementStaticField();
StaticFieldDemo sfd2 = new StaticFieldDemo();
sfd2.NormalMethodincrementStaticField();
}
}
输出结果
static field staticVar = 1
static field staticVar = 2
2. static method uses static field => fine
public class StaticFieldDemo {
public static int staticVar;
public int instanceVar;
/*
* test2 static method uses static field
*/
public static void staticMethodIncrementStaticFields() {
++staticVar;
System.out.println("static Method increments static fields in static method : " + staticVar);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
/**/
//test2
StaticFieldDemo.staticMethodIncrementStaticFields();
StaticFieldDemo.staticMethodIncrementStaticFields();
}
}
输出结果
static Method increments static fields in static method : 1
static Method increments static fields in static method : 2
3. static method uses normal fields => compilation error
public class StaticFieldDemo {
public static int staticVar;
public int instanceVar;
/**/
//test3 static method uses normal fields => compilation error
public static void staticMethodIncrementNormalFields() {
++instanceVar; // compilation error
System.out.println("static Method increments static fields in static method : " + staticVar);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//test 3...
}
}
4. normal method uses normal fields => fine, but nothing special