在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP