有 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;
}

共 (1) 个答案

  1. # 1 楼答案

    假设下一节课

    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;
    }
    

    您将无法获得预期的值:

    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. 按顺序阻止执行和字段初始化
    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
        }
    }
    

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