简体   繁体   English

Java中静态变量和初始化顺序的文本顺序

[英]Textual order of static variables and initialization order in Java

I only spend five minutes to find a duplicate in SO. 我只花了五分钟在SO中找到一份副本。

My question is simple. 我的问题很简单。 Does the following code always work? 以下代码是否始终有效?

public class LexicalOrderStatic {
    private static Integer a1 = initA1();

    private static Integer a2 = initA2();


    private static Integer initA2(){
        return new Integer(5) / a1;
    }

    private static Integer initA1(){
        return new Integer(5);
    }

    public Integer getA1(){
        return new Integer(a2);
    }

    public static void main(String[] args) {
        LexicalOrderStatic lexLuthor = new LexicalOrderStatic();
        System.out.println(lexLuthor.getA1());

    }
}

In java can I be sure that a1 is always initialized before a2 ? 在java中我可以确定a1 总是在a2之前初始化吗?

Thanks. 谢谢。 Dw is ok if it is asked or if it is very simple. 如果被问到或者它是否非常简单,Dw就可以了。

In java can I be sure that a1 is always initialized before a2 ? 在java中我可以确定a1总是在a2之前初始化吗?

Yes, because the specification (section 12.4.2) guarantees it (emphasis mine): 是的,因为规范(第12.4.2节)保证它(强调我的):

Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order , as though they were a single block. 接下来, 按文本顺序执行类的类变量初始值设定项和类的静态初始值设定项,或接口的字段初始值设定项,就好像它们是单个块一样。

Note that constants are initialized earlier than non-constants (step 6 compared with step 9 quoted above). 请注意, 量比非常量更早初始化(步骤6与上面引用的步骤9相比)。

Yes. 是。 The chain of elements group ( name of the class, static attributes, instance attributes, static method, inner static block of code, etc) (1) is defined in compile time, not in run time: it has a deterministic behaviour. 元素链组(类的名称,静态属性,实例属性,静态方法,内部静态代码块等) (1)在编译时定义,而不是在运行时定义:它具有确定性行为。

When you run main , you have loaded at the first time LexicalOrderStatic and the static elements (attributes, methods) are loaded very quickly if this is the first loading. 运行main时 ,如果这是第一次加载,则第一次加载LexicalOrderStatic和静态元素(属性,方法)非常快。

If you load a second obejct of LexicalOrderStatic , the attribute are shared between the two instance. 如果加载LexicalOrderStatic的第二obejct,属性在两个实例之间共享。

Yu can see this statement in running this modified main Yu可以在运行此修改后的main中看到此语句

public static void main(String[] args) {
    LexicalOrderStatic lexLuthor = new LexicalOrderStatic();
    System.out.println(lexLuthor.getA1());
    LexicalOrderStatic lexLuthor2 = new LexicalOrderStatic();
    System.out.println(lexLuthor2.getA1());
}

(1) before I referred to inheritance, but it'snt the situation, as pointed by the first comment (1)在我提到继承之前,但正如第一条评论所指出的那样

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

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