简体   繁体   中英

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?

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. 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:

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.

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.

Simple. Since they are final , you would not be able to modify them later, so the default value would also be, well, final. You would not be allowed to modify it later. Not very useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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