简体   繁体   English

为什么最终实例变量不需要初始化,而最终局部变量不需要初始化?

[英]Why does a final instance variable require initialization, when a final local variable does not?

The following example class does not compile: 以下示例类无法编译:

class Test {
    final int x;  // Compilation error: requires initialization.
}

The compilation error message for this code is: 此代码的编译错误消息是:

..\src\pkgs\main\Test.java:3: error: variable x might not have been initialized
class Test {
^

However, Java does not generate any error message for a class that contains the following method: 但是,Java不会为包含以下方法的类生成任何错误消息:

class Test {
    void method() {
        final int x;  // Compiles OK; has no initialization.
    }
}

Regarding initialization and its requirement, why does Java treat final instance variables and final local variables differently? 关于初始化及其要求, Java为什么要以不同的方式对待最终实例变量和最终局部变量? Thanks. 谢谢。

An instance variable is implicitly used by the instance. 实例隐式使用实例变量。 The local variable example you gave isn't using the local variable, so there's no error (the variable isn't used). 您提供的局部变量示例未使用局部变量,因此没有错误(未使用该变量)。

Your local variable example will fail to compile (with the same error) if you try to use x : 如果您尝试使用 x则您的局部变量示例将无法编译(具有相同的错误):

class Test {

    Test() {
        final int x;
        System.out.println(x); // <== Compilation error - "variable x might not have been initialized"
    }
}

Similarly, your first example is fine provided you do initialize the variable at some point, not necessarily in the declaration: 同样,您的第一个示例很好,只要您确实在某个时候初始化变量,而不必在声明中初始化:

class Test {
    final int x;

    Test() {
        this.x = 10;
    }
}

Any use , ie read, of the second case would give you an error . 第二种情况的任何使用 (即读取) 都会给您带来错误 But unused variables count as a warning, not an error; 但是未使用的变量被视为警告,而不是错误。 the meaning of the code that runs is unambiguous, if quite likely wrong. 如果很可能是错误的,则运行的代码的含义是明确的。

For the constructor case, there isn't that kind of unused variable analysis performed by the compiler, if only because (for anything except private fields) it might be read in another file the compiler doesn't have access to. 对于构造函数而言,编译器不会执行这种未使用的变量分析,仅是因为(对于私有字段以外的任何内容而言)它可能会在编译器无法访问的另一个文件中读取。

So it needs to be trapped as an error to avoid run-time behaviour that would end up depending on unspecified JVM implementaion details. 因此,必须将其捕获为错误,以避免运行时行为最终取决于未指定的JVM实现细节。

Final attricutes should be initialized in constructors, that's why it does not compile in your example. 最终属性应在构造函数中初始化,这就是为什么它不能在您的示例中编译的原因。 Final variable should be also initialized before being used. 最终变量在使用前也应进行初始化。 It's fine to declare it method with not initialization. 不用初始化就可以声明它的方法。

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

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