Java中lambda表达式的作用域规则是什么?
Java中的lambda表达式有不同的作用域规则。在lambda表达式中,this 和super 关键字在词法上是范围内的,这意味着该关键字 引用了封闭类型的对象,而super关键字则引用了封闭的超类。对于匿名类,它们是相对于匿名类本身的。同样,在lambda表达式中声明的局部变量与在封闭类中声明的变量冲突。在使用匿名类的情况下,允许它们在封闭的类中隐藏变量。
示例
@FunctionalInterface
interface TestInterface {
int calculate(int x, int y);
}
class Test {
public void showValue(String str) {
System.out.println("The value is: " + str);
}
}
public class LambdaExpressionTest extends Test {
public static void main(String[] args) {
LambdaExpressionTest lambdaObj = new LambdaExpressionTest();
lambdaObj.getResult();
}
public void getResult() {
TestInterface ref = (x, y) -> { // lambda expression
System.out.println("The toString: " + this.toString());
super.showValue("Calling from Lambda");
return x*y;
};
System.out.println("Result is: " + ref.calculate(8, 6));
}
}输出结果
The toString: LambdaExpressionTest6@87aac27 The value is: Calling from Lambda Result is: 48
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短