实例变量初始化器的排序 [英] Ordering of instance variable initializers

查看:130
本文介绍了实例变量初始化器的排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,似乎很清楚,实例变量intitializers 按照它们在类声明中出现的顺序执行。

It seems intuitively clear that in Java, instance variable intitializers are executed in the order in which they appear in the class declaration.

这肯定是JDK中的情况我在用。例如,以下内容:

This certainly appears to be the case in the JDK I am using. For example, the following:

public class Clazz {
    int x = 42;
    int y = this.z;
    int z = this.x;
    void print() {
        System.out.printf("%d %d %d\n", x, y, z);
    }
    public static void main(String[] args) {
        new Clazz().print();
    }
}

打印 42 0 42 (换句话说, y 选择默认值 z )。

prints 42 0 42 (in other words, y picks up the default value of z).

这个订单实际上是否有保证?我一直在查看JLS,但找不到任何明确的确认。

Is this ordering actually guaranteed? I've been looking through the JLS, and can't find any explicit confirmation.

推荐答案

是的,确实如此。

se7 JLS涵盖 12.5执行部分:

The se7 JLS covers instance variable initialization order in the 12.5 Execution section:


...

4.为此类执行实例初始值设定项和实例变量初始值设定项,将实例变量
初始值设定项的值分配给相应的实例变量,按
从左到右的顺序排列在课程的源代码
中以文本形式出现。如果执行任何这些初始化程序导致
异常,则不会处理其他初始化程序,并且此
过程会突然完成同样的异常。否则,
继续第5步。

...

...
4. Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5.
...

JLS for Java 5 在类部分中提到:


静态初始值设定项和类变量初始值设定项按文本顺序执行$ ​​b $ b。

The static initializers and class variable initializers are executed in textual order.

这篇关于实例变量初始化器的排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆