为什么最终的静态变量不能在实例块中赋值?

Pra*_*nna 3 java

class Test {
    static final String name;

    {    
        name = "User"; 
        /* shows error. As i have to assign User as default value */
    }
    final String name1;

    {
       name1 = "User"; // This works but why the above one does not works
    }
}    
Run Code Online (Sandbox Code Playgroud)

我能够使用静态块分配值,但不能通过实例阻止为什么?

eri*_*cbn 5

因为它是static final,所以它必须在静态上下文中初始化一次 - 声明变量时或在静态初始化块中.

static {    
    name = "User";
}
Run Code Online (Sandbox Code Playgroud)

编辑:静态成员属于该类,非静态成员属于该类的每个实例.如果要在实例块中初始化静态变量,则每次创建该类的新实例时都会初始化它.这意味着它在此之前不会被初始化,并且可以多次初始化.因为它是staticfinal,它必须初始化一次(对于那个类,不是每个实例一次),所以你的实例块不会.

也许您想要更多地研究Java中的静态变量和非静态变量.

EDIT2:以下是可能有助于您理解的示例.

class Test {
    private static final int a;
    private static int b;
    private final int c;
    private int c;

    // runs once the class is loaded
    static {
        a = 0;
        b = 0;
        c = 0;  // error: non-static variables c and d cannot be
        d = 0;  // referenced from a static context
    }

    // instance block, runs every time an instance is created
    {
        a = 0;  // error: static and final cannot be initialized here
        b = 0;
        c = 0;
        d = 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

所有未注释的行都有效.如果我们有

    // instance block
    {
        b++; // increment every time an instance is created
        // ...
    }
Run Code Online (Sandbox Code Playgroud)

然后b将作为创建的实例数的计数器,因为它static在非静态实例块中增加并递增.