实例变量定义和实例块 [英] instance variable definitions and instance blocks

查看:123
本文介绍了实例变量定义和实例块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码 -

{s = "Hello";}
String s;

这编译得很好,这意味着变量定义在实例阻止之前执行。
但是,如果我使用以下代码,它不会编译(错误:非法转发参考)。

This compiles fine, implying that the variable definitions are executed before the instance blocks. However, if I use the following code instead, it does not compile ("error: illegal forward reference").

{s = "Hello"; String ss = s;}
String s;

因此无法在右侧使用's'的值在变量
定义之前出现的实例块中的语句。对幕后发生的事情有一个明智的解释,还是这只是Java的特殊功能?

So it is not possible to use the value of 's' on the right-hand side of a statement in an instance block that comes BEFORE the variable definition. Is there a sane explanation of what is happening behind the scenes, or is this simply an idiosyncratic feature of Java?

P.S。我之前看过一个类似的问题,唯一的解释是它是Java的一个特性。
我写这篇文章是为了询问社区是否确实是这个问题的最后一句话。

P.S. I have seen a similar question asked before, the only explanation given there is that it is a feature of Java. I am writing this to ask the community if that is indeed the final word on this question.

推荐答案

JLS§8.3.3(转发参考文献在字段初始化期间)在这里阐明了一些亮点:

JLS §8.3.3 ("Forward References During Field Initialization") sheds some light here:


使用实例变量,其声明在使用后以文本形式出现有时受限制,即使这些实例变量在范围内。具体来说,如果满足以下所有条件,则为编译时错误:

Use of instance variables whose declarations appear textually after the use is sometimes restricted, even though these instance variables are in scope. Specifically, it is a compile-time error if all of the following are true:


  • 在a中声明实例变量在使用实例变量后,类或接口C以文本方式显示;

  • The declaration of an instance variable in a class or interface C appears textually after a use of the instance variable;

在C的实例变量初始化程序或实例初始化程序中使用是一个简单名称of C;

The use is a simple name in either an instance variable initializer of C or an instance initializer of C;

使用不在作业的左侧;

The use is not on the left hand side of an assignment;

C是封闭使用的最内层的类或接口。

C is the innermost class or interface enclosing the use.

第一个bullet将适用于您的示例。

The first bullet would apply to your example.

至于为什么部分,为什么通常是一个棘手的语言设计问题,但在这种情况下,他们帮助添加了这个进一步说明:

As for the "why" part, "why" is usually a tricky question with language design, but in this case they helpfully added this note further down:


上述限制旨在在编译时捕获循环或其他格式错误的初始化。

The restrictions above are designed to catch, at compile time, circular or otherwise malformed initializations.

这篇关于实例变量定义和实例块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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