【问题标题】:Order in which static variables and methods are declared/called声明/调用静态变量和方法的顺序
【发布时间】:2014-11-15 19:26:12
【问题描述】:

我正在阅读一本关于 Java 的书。它给出了一个这样的例子:

class UseStatic {
    static int a = 3;
    static int b;

    // ... some more lines  

    static {
        b = 4 * a;
    }
}

然后它解释了这一点:

一旦UseStatic 类被加载,所有static 语句运行。首先将a设置为3,然后是静态块 执行,...,然后将 b 初始化为 a*4 或 12。

我想知道这些行的执行顺序到底发生了什么。它如何首先从static int a = 3 的顶部开始,然后才跳过static int bstatic {..},然后才跳回静态int b?它是如何知道这种依赖关系的?

【问题讨论】:

    标签: java static runtime


    【解决方案1】:

    它不会“跳过static int b”,也不会“跳回static int b”。没有什么可以“跳回”,因为static int b 只是一个声明,而不是初始化/分配。它声明了变量,但没有给它赋值。

    首先声明并初始化a。然后声明b。然后执行static 块,为b 赋值。

    Java 语言规范规定了所有这些事情的确切顺序。有关更多信息,请参阅 Jon Skeet 对 Are there any guarantees in JLS about order of execution static initialization blocks? 的回答。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-23
      • 2016-12-15
      • 1970-01-01
      相关资源
      最近更新 更多