Java块、闭包、Lambdas。。。简单解释 对于那些曾经用C、C++或ObjvEEC编写的人来说,理解块非常简单。为什么在Java(8)中获取这个概念如此困难

Java块、闭包、Lambdas。。。简单解释 对于那些曾经用C、C++或ObjvEEC编写的人来说,理解块非常简单。为什么在Java(8)中获取这个概念如此困难,java,lambda,closures,block,Java,Lambda,Closures,Block,我会回答我的问题 你只需要理解“类型” 变量有一个类型。例如: int i, double d… void function () <= this type is: a function with no return and no param. void function (type param) <= this type is: a function with no return with a param of type ‘type’ type function (type pa

我会回答我的问题

你只需要理解“类型”

变量有一个类型。例如:

int i, double d…
void function () <= this type is: a function with no return and no param.
void function (type param) <= this type is: a function with no return with a param of type ‘type’
type function (type param) <= this type is: a function with a return of type ‘type’ and a param of type ‘type’
对象具有类型(类)。例如:

函数有一个类型。例如:

int i, double d…
void function () <= this type is: a function with no return and no param.
void function (type param) <= this type is: a function with no return with a param of type ‘type’
type function (type param) <= this type is: a function with a return of type ‘type’ and a param of type ‘type’
用Java怎么说呢

1/声明块/闭包/lambda的类型

2/创建函数(在类中或不在类中),该函数将该类型作为param获取

3/创建块/闭包/lambda类型的本地函数

4/将其作为参数传递给使用它的函数

例如:

输出

我的班级

消息:MyClass

1

只是一个用大括号括起来的语句列表。这就是全部。块是通过按顺序执行其各个语句来执行的。它与Ruby编程语言中称为“块”的东西完全不同

结束

Java没有闭包,但它有一些类似于闭包的东西:

int limit = ...;

Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
        for (int i=0 ; i<limit ; i++) { ... }
    }
});
Java8引入了
@函数式接口类型的思想,该接口类型必须声明一个方法。在本例中,他们将
java.lang.Runnable
类重新连接为
@Functional


当编译器读取上面的代码时,它知道让匿名类实现
Runnable
接口,因为这是
Thread
构造函数接受的唯一类型,并且它知道lambda的主体应该成为
run()
方法,因为这是唯一的方法,由代码> > Runnaby.< /Cord>/P>这不是一个真正的问题-它不是问一个具体的问题。它也太宽,答案是不准确的在几个地方。java是基于C和C++,所以行为的<代码> {} /代码>是非常相同的。你的怀疑是什么还不清楚。谢谢詹姆斯的贡献。我没有谈论这种类型的块,但因为苹果添加了C,C++和ObjuleC(),这意味着闭包或lambda。所以你解释的不是我所说的那种“块”功能。我没能正确地解释我的想法。
int limit = ...;

Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
        for (int i=0 ; i<limit ; i++) { ... }
    }
});
int limit = ...;
Thread t = new Thread(() -> {
    for (int i=0 ; i<limit ; i++) { ... }
});