java - 静态和最终静态赋值

标签 java variables static variable-assignment final

我用的是同一种概念,我在头等舱用过。
b 被初始化为 0,我在使用 b 的所有地方都得到 0。 一段时间后,我找到了原因并运行调试器,发现 a 在函数调用之前没有分配任何值。变量 a 只有值默认值 0。

但是当我运行类 Test2 时。它给出了输出 5。

我想知道这个初始化是什么时候发生的? 我知道静态变量在编译时获得值(value)。但是静态最终呢? 这个变量什么时候得到它的值?

public class Test1 {

    static int b=add();
    static int add()
    {
        return a;
    }
    static int a=5;

    public static void main(String[] args) {        
        System.out.println(b);
    }
}
//Gives output 0


public class Test2 {

    static int b=add();
    static int add()
    {
        return a;
    }
    final static int a=5;

    public static void main(String[] args) {    
        System.out.println(b);
    }
}

//gives output 5

最佳答案

来自 12.4.2 部分在Java Language Specifications中,初始化Class的过程如下:

  • Then, initialize the final class variables and fields of interfaces whose values are compile-time constant expressions (§8.3.2.1, §9.3.1, §13.4.9, §15.28).
  • 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.

因此最终变量将在静态变量之前被初始化。你将得到输出 5

关于java - 静态和最终静态赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30364806/

相关文章:

Java:求二维数组的总和

java - 创建不可变队列的问题

PHP:处理 MySQL 连接变量

javascript - 继续获取 "Unexpected token ,"以及变量中的坐标

c# - 从非静态方法构建静态委托(delegate)

c# - ASP.NET 中的静态 C# 类变量是什么?

java - HTML 标签未反射(reflect)在 Gxt Grid 中

java - 使用日期更改按钮的文本

PHP,最好在if之前设置变量还是使用if/else?

java - 静态函数的线程安全