Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中静态变量的文本顺序和初始化顺序_Java - Fatal编程技术网

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

Java中静态变量的文本顺序和初始化顺序,java,Java,我只花了五分钟在SO中找到了一个副本 我的问题很简单。以下代码是否始终有效 public class LexicalOrderStatic { private static Integer a1 = initA1(); private static Integer a2 = initA2(); private static Integer initA2(){ return new Integer(5) / a1; } private

我只花了五分钟在SO中找到了一个副本

我的问题很简单。以下代码是否始终有效

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());

    }
}
在java中,我能否确保a1总是在a2之前初始化

谢谢。如果有人问Dw,或者Dw非常简单,那么Dw是可以的

在java中,我可以确保a1总是在a2之前初始化吗

是的,因为规范保证(强调我的):

接下来,按照文本顺序执行类的类变量初始值设定项和静态初始值设定项,或者执行接口的字段初始值设定项,,就像它们是单个块一样

请注意,常量的初始化时间早于非常量的初始化时间(步骤6与上面引用的步骤9相比)。

是。 元素链组(类名称、静态属性、实例属性、静态方法、内部静态代码块等)(1)在编译时定义,而不是在运行时:它具有确定性行为

运行main时,您第一次加载了LexicalOrderStatic,如果这是第一次加载,静态元素(属性、方法)会很快加载

如果加载LexicalOrderStatic的第二个obejct,则该属性将在两个实例之间共享

Yu可以在运行这个修改过的main中看到这个语句


(1) 在我提到继承之前,但情况并非如此,正如第一条评论所指出的那样,

很荣幸得到您的回答,先生:)文本顺序到底是什么意思?@Bato BairTsyrenov:它们在源代码中出现的顺序。源代码中
a1
的声明出现在
a2
的声明之前,因此它首先被初始化。不清楚这里“继承链”的确切含义是什么,也不清楚它为什么相关-本例中没有使用继承。
public static void main(String[] args) {
    LexicalOrderStatic lexLuthor = new LexicalOrderStatic();
    System.out.println(lexLuthor.getA1());
    LexicalOrderStatic lexLuthor2 = new LexicalOrderStatic();
    System.out.println(lexLuthor2.getA1());
}