简体   繁体   English

什么是Java中静态字段的初始化程序

[英]What is initializers for static fields in Java

I have got the following line from Oracle Java tutorial You can find this here Execution under the heading "12.4. Initialization of Classes and Interfaces" 我从Oracle Java教程得到以下代码你可以在这里找到这个在“12.4。类和接口的初始化”标题下的执行

Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class. 类的初始化包括执行其静态初始化程序和类中声明的静态字段(类变量)的初始化程序。

It will be great if someone explain me How "initializers for static fields" is referring to "class variables". 如果有人向我解释如何“静态字段的初始化器”指的是“类变量”,那将会很棒。

A "class variable" is a variable that is declared as a static property of a class. “类变量”是声明为类的static属性的变量。 By "initializers for static fields" they are referring to the initialization of these static variables, which happens when the class is loaded. 通过“静态字段的初始化器”,它们指的是这些静态变量的初始化,这种情况在加载类时发生。 Here's an example: 这是一个例子:

public class MyClass {
    private static int num = 0; //This is a class variable being initialized when it is declared
}

Another way to initialize static fields is to use static blocks: 初始化静态字段的另一种方法是使用静态块:

public class MyClass {
    private static int num;
    static {
        num = 0; //This a class variable being initialized in a static block
    }
}

These static blocks are run from top to bottom when the class is loaded. 加载类时,这些静态块从上到下运行。

In the end, the quote is trying to say that "class variable" is just another name for "static field." 最后,引用试图说“类变量”只是“静态字段”的另一个名称。

A static member is a variable that belongs to the class as a whole, not a specific instance. static成员是一个整体属于该类的变量,而不是特定的实例。 It's initialized once, when the classloader loads the class. 当类加载器加载类时,它被初始化一次。

Eg: 例如:

public class MyClass {
    // Note the static modifier here!
    private static int someVariable = 7;
}

One common usecase for such variables is static final members of immutable types or primitives used to represent constants: 这些变量的一个常见用例是不可变类型的static final成员或用于表示常量的基元:

public class Human {
    public static final String SPECIES = "Homo sapiens";
    public static final int LEGAL_DRINKING_AGE = 21; // U.S centric code :-(
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM