更新时间:2022-05-31 03:37:05
static
成员属于类而不是特定实例.
static
members belong to the class instead of a specific instance.
这意味着 只有一个 static
字段的实例存在[1] 即使您创建了该类的一百万个实例或您不要创建任何.它将被所有实例共享.
It means that only one instance of a static
field exists[1] even if you create a million instances of the class or you don't create any. It will be shared by all instances.
由于static
方法也不属于特定实例,因此它们不能引用实例成员.在给出的示例中,main
不知道它应该引用 Hello
类的哪个实例(以及Clock
类的哪个实例).static
成员只能引用 static
成员.实例成员当然可以访问 static
成员.
Since static
methods also do not belong to a specific instance, they can't refer to instance members. In the example given, main
does not know which instance of the Hello
class (and therefore which instance of the Clock
class) it should refer to. static
members can only refer to static
members. Instance members can, of course access static
members.
旁注:当然,static
成员可以通过对象引用访问实例成员.
Side note: Of course, static
members can access instance members through an object reference.
示例:
public class Example {
private static boolean staticField;
private boolean instanceField;
public static void main(String[] args) {
// a static method can access static fields
staticField = true;
// a static method can access instance fields through an object reference
Example instance = new Example();
instance.instanceField = true;
}
[1]:根据运行时特性,每个 ClassLoader、AppDomain 或线程都可以是一个,但这不是重点.
[1]: Depending on the runtime characteristics, it can be one per ClassLoader or AppDomain or thread, but that is beside the point.