java - Java中非法前向引用的问题

标签 java

<分区>

为什么当我在变量声明中使用引用 this 时,不出现非法前向引用?使用 this 和不使用它的声明有什么区别?

以下示例由于非法前向引用而无法编译:

class FailsToCompile {
    int a = b; //illegal forward reference
    int b = 10;
}

通过限定 thisb 的使用,编译错误消失了。

class Compiles {
    int a = this.b; //that's ok
    int b = 10;
}

最佳答案

假设下面的类

public class MyClass {
    int a = b;
    int b = 10;
}

JLS 8.3.3.在你的情况下状态:

Use of instance variables whose declarations appear textually after the use is sometimes restricted
- The use is a simple name in either an instance variable initializer of C or an instance initializer of C

现在,使用成员 this 允许您访问已声明为默认值(a = 0, b = 0)但尚未完全初始化的实例.如果您检查以下结果,这是可见的:

public class MyClass {
    int a = this.b;
    int b = 10;
}

你不会得到预期的值(value):

new MyClass().a //0
new MyClass().b //10

我无法解释为什么这是合法的,因为这永远不会给出正确的值。我们可以找到一些关于为什么存在限制的解释:

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

但是为什么允许 this 工作...


知道在实例初始化期间,会发生以下操作:

  1. 成员声明
  2. 按顺序执行 block 和Field初始化
  3. 构造函数执行

给出一些奇怪的行为:

public class MyClass {

    {
        b = 10;
    }
    int a = this.b;
    int b = 5;
    {
        b = 15;
    }

    public static void main(String[] args) {
        MyClass m = new MyClass();
        System.out.println(m.a); //10
        System.out.println(m.b); //15
    }
}

我会限制构造函数中的初始化。

关于java - Java中非法前向引用的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55949615/

相关文章:

java - 从文件中读取最后一个字节并截断大小

java - 在java中遍历列表的列表

java - 尝试添加 Jackson 库时出现 BeanCreationException

java - 将具有两个字段的类和具有单个参数的构造函数重写为记录类

java - 共享健康插件 Bukkit

java - Magnolia JCR 获取 LinkedList 属性项

java - java中如何避免空指针异常

java - org.hibernate.exception.GenericJDBCException : could not execute statement

java - 网络浏览器插件和java小程序?

java - Hello world 可以运行,但随后出现没有主线的错误?