我们可以在Java的lambda表达式中访问哪种变量?
lambda表达式由两个部分组成,一个是参数 ,另一种是一个表达 ,并且这两个部件都用箭头分离(->)符号。Lambda表达式可以访问其封闭 范围的变量。
Lambda表达式访问这两个实例 和静态 的变量,它是包类,也可以访问本地 变量 它们是有效的最终或最后。
语法
( argument-list ) -> expression
示例
interface TestInterface {
void print();
}
public class LambdaExpressionTest {
int a; // instance variable static int b; // static variable LambdaExpressionTest(int x) { // constructor to initialise instance variable this.a = x;
}
void show() {
// lambda expression to define print() method TestInterface testInterface = () -> { // accessing of instance and static variable using lambda expression System.out.println("Value of a is: "+ a);
System.out.println("Value of b is: "+ b);
};
testInterface.print();
}
public static void main(String arg[]) {
LambdaExpressionTest test = new LambdaExpressionTest(10);
test.show();
}
}输出结果
Value of a is: 10 Value of b is: 0
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短