本文介绍了Java编译器允许使用'this'关键字访问未初始化的空白final字段吗?这是一个错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了这段代码,看来编译器允许在使用'this'关键字访问时访问未初始化的空白final字段:

I wrote this piece of code and it seems compiler allows accessing uninitialized blank final field when accessed using 'this' keyword:

public class TestClass
{
    public final int value1;
    public int value2;

    TestClass(int value) {
        value2 = 2 + this.value1; // access final field using 'this' before initialization gives no compiler error
        //value2 = 2 + value1;      // uncomment it gives compile time error - variable value1 might not have been initialized
        value1 = value;
    }

    public static void main(String args[]) {
    TestClass tc = new TestClass(10);
    System.out.println("\nTestClass Values : value1 =  " + tc.value1 + " , value2 =  " + tc.value2);
    }
}

我尝试在1.5、1.6和& 1.7,并且在所有三个结果中都得到相同的结果.

I tried compiling it on 1.5, 1.6, & 1.7 and got same result in all three of them.

对我来说,它看起来像是编译器错误,因为在这种情况下编译器必须抛出错误,但使用'this'关键字则不会,因此会产生编码错误的范围,因为程序员不会注意到它,因为没有编译时或运行时时错误将被抛出.

To me it looks like compiler bug because compiler must throw error in this case but with 'this' keyword it doesn't and thus creates scope of coding error as it will go unnoticed by the programmer since no compile-time or run-time error will be thrown.

为什么不是重复的几点
-所有答案都在解释它的工作原理以及JLS所说的话,很好,但是我的真正意图是首先应该允许这样做?
-我的问题更多是从程序员的角度出发,而不是语言语义

FEW POINTS WHY IT IS NOT A DUPLICATE
- all answers are explaining how it works and what JLS says, fine, but my real intent here is should that be allowed at the first place?
- my question here is more from programmer's point of view and not language semantics

推荐答案

这不是错误.这是Java规范1.6及更低版本的功能.

This is not a bug. This a feature for Java Specification 1.6 and lower.

可以在代码的任何部分访问final字段.没有任何限制.

The final field can be accessed at any part of the code. There is no restriction about it.

final的唯一限制是必须在创建类实例之前对其进行初始化.

The only restriction in case of final is that it has to be initialized before class instance is created.

使用this时,表示它是正在构造的对象的元素.

When you use this, you express that it is element of the object that is being constructed.

从1.7版本开始由于更改我们可以说这是某些编译器实现中的错误.

Since the specification 1.7 because of change we may say that this is bug in some implementation of compilers.

但是从1.8开始,该代码将对this.value1value1产生相同的错误.

But since 1.8 the code will produce same error for this.value1 or value1.

这篇关于Java编译器允许使用'this'关键字访问未初始化的空白final字段吗?这是一个错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:10