我们可以在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
热门推荐
3 拳友的祝福语简短
10 爸爸生日转帐祝福语简短
11 生日祝福语大全简短老人
12 新年拜年祝福语英文简短
13 春节简短祝福语二十字
14 退休祝福语事业文案简短
15 口红新婚祝福语简短女性
16 好朋友订婚祝福语简短
17 队长生日祝福语简短
18 给求婚的祝福语简短