简体   繁体   English

Java中的静态最终变量初始化

[英]static final variable initialization in java

I have a doubt in static final variable.In the following program: 我对静态最终变量有疑问。在以下程序中:

class StaticPuzzel2 {
    public static void main (String[] args) {
    }
    final static int i;
    static {
            System.out.print ("\n\t"+ StaticPuzzel2.i);
            i = 11;
            System.out.print ("\n\t"+ StaticPuzzel2.i);
            System.out.print ("\n\t"+ i);
    }
}

Even though the final variable has not been initialized it is not throwing error. 即使最终变量尚未初始化,也不会引发错误。 Why it is so? 为什么会这样呢?

I assume you're wondering why it doesn't throw an error when you access it before setting it to 11 . 我假设您想知道为什么在将其设置为11之前访问它时,它不会引发错误。 The reason is, that the variable is actually initialized with the default value (zero), and changed at runtime just like any other variable. 原因是,该变量实际上是使用默认值(零)初始化的,并且像其他任何变量一样在运行时进行更改。

When using a static initialization block, the final modifier only makes sure you are assigning a value to the variable only once. 当使用静态初始化块时, final修饰符仅确保您仅向变量分配一个值。 What it doesn't do, is making it non-existent before that has happened. 它不做的是在此事发生之前使其不存在。

You are initializing static variable in static block. 您正在static块中初始化static变量。 That's why. 这就是为什么。

Try this: final static int i = 0; 试试这个: final static int i = 0;

From java specs : 从Java规范:

A variable can be declared final. 可以将变量声明为final。 A final variable may only be assigned to once. 最终变量只能分配一次。 It is a compile-time error if a final variable is assigned to unless it is definitely unassigned immediately prior to the assignment 如果分配了最终变量,则将导致编译时错误,除非在分配之前立即将其绝对取消分配

So it doesn't actually means that if should be initialized at declaration. 因此,这实际上并不意味着if应该在声明时初始化。 But it means that it can only be assigned once and this assignment can be part of declaration or initializer blocks as in your case. 但这意味着它只能分配一次,并且这种分配可以像您的情况一样是声明或初始化程序块的一部分。 This is will give you error now. 这会给你错误。

You can check this answer for more details. 您可以检查此答案以获取更多详细信息。 Java - Can final variables be initialized in static initialization block? Java-最终变量可以在静态初始化块中初始化吗?

Because it has been already initialized in static block. 因为它已经在静态块中初始化过。 If you comment out that line it will give a compilation error. 如果您注释掉该行,则会出现编译错误。

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

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