简体   繁体   English

为什么静态最终变量不是默认值?

[英]Why aren't static final variables given default values?

Why aren't static final variables given default values, whereas static (but non-final variables are given default values). 为什么静态最终变量不是默认值,而静态(但非最终变量是默认值)。

What is the reason that such behavior was implemented in Java? 这种行为是用Java实现的原因是什么?

Of course static final variables are given default values, see for example this: 当然,静态最终变量被赋予默认值,例如参见:

class Test {
    static final int x;
    static {
        printX();
        x = 42;
        printX();
    }

    static void printX() {
        System.out.println("Here x is "+x);
    }
    public static void main(String[] args) { }
}

The output is: 输出是:

Here x is 0
Here x is 42

If x wasn't given the default value of 0 as specified in JLS 4.12.5 , the output would depend on the JVM used. 如果未按照JLS 4.12.5中的规定为x指定默认值0 ,则输出将取决于所使用的JVM。 You might see some random number. 您可能会看到一些随机数。

Update : Now that we have demonstrated that static final fields do get a default value, you may want to know why the default value is not enough. 更新 :现在我们已经证明静态最终字段确实获得了默认值,您可能想知道为什么默认值不够。 There is no good answer to that question, besides the obvious one: "The spec says so" . 除了显而易见的问题之外,这个问题没有一个好的答案: “规范是如此” Excerpt from 8.3.1.2: 摘录自8.3.1.2:

It is a compile-time error if a blank final (§4.12.4) class variable is not definitely assigned (§16.8) by a static initializer (§8.7) of the class in which it is declared. 如果空白的final(§4.12.4)类变量未被声明它的类的静态初始化程序(第8.7节)明确赋值(第16.8节),则为编译时错误。

We can only guess at the motivation behind such a restriction, but I think it's to make programs easier to understand. 我们只能猜测这种限制背后的动机,但我认为这是为了让程序更容易理解。 If you want to set the variable to 0 it's clearer to do it explicitly. 如果要将变量设置为0,则可以更明确地执行此操作。

Simple. 简单。 Since they are final , you would not be able to modify them later, so the default value would also be, well, final. 由于它们是final ,您将无法在以后修改它们,因此默认值也将是最终的。 You would not be allowed to modify it later. 您将无法在以后修改它。 Not very useful. 不是很有用。

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

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