Java 编译器允许使用“this"关键字访问未初始化的空白最终字段?这是一个错误吗? [英] Java compiler allows accessing uninitialized blank final field using 'this' keyword? Is this a bug?

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

问题描述

我写了这段代码,似乎编译器允许在使用this"关键字访问时访问未初始化的空白最终字段:

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("
TestClass 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.

可以在代码的任何部分访问最终字段.对此没有任何限制.

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"关键字访问未初始化的空白最终字段?这是一个错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆