static
members belong to the class instead of a specific instance.
(static
成员属于该类,而不是特定的实例。)
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.
(这意味着,即使您创建了该类的一百万个实例,也没有创建任何static
实例) ,但仅存在一个static
字段实例) [1] 。)
It will be shared by all instances. (它将被所有实例共享。)
Since static
methods also do not belong to a specific instance, they can't refer to instance members.
(由于static
方法也不属于特定实例,因此它们不能引用实例成员。)
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. (在给出的示例中, main
不知道应引用Hello
类的哪个实例(以及Clock
类的哪个实例)。)
static
members can only refer to static
members. (static
成员只能引用static
成员。)
Instance members can, of course access static
members. (实例成员当然可以访问static
成员。)
Side note: Of course, static
members can access instance members through an object reference) . 旁注:当然, static
成员可以通过对象引用)访问实例成员。)
Example:
(例:)
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]: Depending on the runtime characteristics, it can be one per ClassLoader or AppDomain or thread, but that is beside the point.
([1]:根据运行时的特性,每个ClassLoader或AppDomain或线程可以是一个,但是那不是重点。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…