gpt4 book ai didi

java - 正在访问哪个变量,本地或类级别?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:13:12 24 4
gpt4 key购买 nike

考虑 Lambda Expressions 中给出的以下代码:

import java.util.function.Consumer;

public class LambdaScopeTest {

public int x = 0;

class FirstLevel {

public int x = 1;

void methodInFirstLevel(int x) {

// The following statement causes the compiler to generate
// the error "local variables referenced from a lambda expression
// must be final or effectively final" in statement A:
//
// x = 99;

Consumer<Integer> myConsumer = (y) ->
{
System.out.println("x = " + x); // Statement A
System.out.println("y = " + y);
System.out.println("this.x = " + this.x);
System.out.println("LambdaScopeTest.this.x = " +
LambdaScopeTest.this.x);
};

myConsumer.accept(x);

}
}

public static void main(String... args) {
LambdaScopeTest st = new LambdaScopeTest();
LambdaScopeTest.FirstLevel fl = st.new FirstLevel();
fl.methodInFirstLevel(23);
}
}

在 JavaDocs 中写道:

suppose that you add the following assignment statement immediately after the methodInFirstLevel definition statement:

 void methodInFirstLevel(int x) {
x = 99;
// ... }

Because of this assignment statement, the variable FirstLevel.x is not effectively final anymore. As a result, the Java compiler generates an error message similar to "local variables referenced from a lambda expression must be final or effectively final" where the lambda expression myConsumer tries to access the FirstLevel.x variable:

System.out.println("x = " + x);

我无法理解 System.out.println("x = "+ x)(语句 A)如何访问 FirstLevel.x?不应该是methodInFirstLevel(int x)方法中传入的x吗?

最佳答案

这似乎是教程中的一个错误。我认为该段落应为:

Because of this assignment statement, the parameter x is not effectively final anymore. As a result, the Java compiler generates an error message similar to "local variables referenced from a lambda expression must be final or effectively final" where the lambda expression myConsumer tries to access the x parameter:

System.out.println("x = " + x);

我的论点基于两个观察:引用的错误消息说“局部变量”,它可能包括参数,但不包括字段。引用的 print 语句打印 23,这是参数的值,而不是 FirstLevel.x 的值。

关于java - 正在访问哪个变量,本地或类级别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40716709/

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