gpt4 book ai didi

java - 实例变量定义和实例 block

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:25:21 24 4
gpt4 key购买 nike

我有以下一段代码-

{s = "Hello";}
String s;

这编译得很好,这意味着变量定义在实例 block 之前执行。但是,如果我改用以下代码,它不会编译(“错误:非法前向引用”)。

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

所以不可能在变量之前的实例 block 中的语句右侧使用's'的值定义。对于幕后发生的事情是否有合理的解释,或者这仅仅是 Java 的一个特殊功能?

附言我之前看到过类似的问题,唯一的解释是它是 Java 的一个特性。我写这篇文章是为了询问社区这是否确实是这个问题的最终决定。

最佳答案

JLS §8.3.3 ("Forward References During Field Initialization")在这里阐明一些光:

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:

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

  • 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 is the innermost class or interface enclosing the use.

第一个项目符号适用于您的示例。

至于“为什么”部分,“为什么”通常是语言设计中的一个棘手问题,但在这种情况下,他们有帮助地进一步添加了这条注释:

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

关于java - 实例变量定义和实例 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25895514/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com