静态和实例(非静态)字段有很不同的含义,在决定使用哪个字段之前了解它们非常重要。
静态变量或方法属于一个类,而不属于该类的特定实例。每个类有一个副本(无论您创建多少个实例),并且可以在没有该类的实例的情况下访问它。例如,
public class MyClass {
static int myInt = 5;
}
System.out.println(MyClass.myInt); // this prints 5
MyClass.myInt = 10;
System.out.println(MyClass.myInt); // this prints 10
一个实例变量需要类
public class MyClass {
private int myInt2;
public void setMyInt2(int val) {
myInt2 = val;
}
public int getMyInt2() {
return myInt2;
}
}
MyClass m1 = new MyClass();
MyClass m2 = new MyClass();
System.out.println(m1.getMyInt2()); // prints 0, the default value
System.out.println(m2.getMyInt2()); // prints 0, the default value
m1.setMyInt2(3);
m2.setMyInt2(5);
// each object operates on its own instance of the variable
System.out.println(m1.getMyInt2()); // prints 3
System.out.println(m2.getMyInt2()); // prints 5
另外的实例,也没有这样的东西作为一个static constructor.
有构造以及静态初始化块。静态初始化块被写为:
static {
// initialize some static members here
}
一般而言,使用实例变量/方法时的值影响的对象的单个实例,并使用静态变量和方法时,他们没有。
你能说清楚,如果你想有一个C#,Java或比较答案。 – 2010-09-14 16:27:12