需要解释如何在java-8中为lambda创建接口对象吗
我是java函数编程新手。在找到此代码 我想知道发生了什么事:需要解释如何在java-8中为lambda创建接口对象吗,lambda,interface,java-8,Lambda,Interface,Java 8,我是java函数编程新手。在找到此代码 我想知道发生了什么事: Ball b = () -> { System.out.println("You hit it!"); }; 接口正在实例化吗 完整示例: public class LambdaBall { public static void main(String[] args) { Ball b = () -> { System.out.println("You hit it!"); }; b.hit(); }
Ball b = () -> { System.out.println("You hit it!"); };
接口正在实例化吗
完整示例:
public class LambdaBall {
public static void main(String[] args) {
Ball b = () -> { System.out.println("You hit it!"); };
b.hit();
}
interface Ball {
void hit();
}
}
这是初始化接口的旧匿名类方法
Ball b = new Ball() {
public void hit(){
System.out.println("You hit it!");
}
}
兰巴斯会这样做
Ball b = () -> System.out.println("You hit it!");
这是初始化接口的旧匿名类方式
Ball b = new Ball() {
public void hit(){
System.out.println("You hit it!");
}
}
兰巴斯会这样做
Ball b = () -> System.out.println("You hit it!");
在Java8之前,定义接口方法的匿名方法是
Ball b = new Ball() {
@Override
public void hit(){
System.out.println("You hit it!");
}
}
自Java8诞生以来,您就可以将函数定义传递给函数
Ball b = () -> System.out.println("You hit it!");
上面的一行懒散地定义了Ball接口的hit()。请注意,这是惰性评估的。删除行b.hit()
您会注意到“you hit it!”根本无法在控制台中打印出来。
然而,这是一个幼稚的例子,您应该避免编写System.out.println()或简单地说函数代码中的副作用会污染您的环境。尽可能地发挥你的作用 在Java8之前,定义接口方法的匿名方式是
Ball b = new Ball() {
@Override
public void hit(){
System.out.println("You hit it!");
}
}
自Java8诞生以来,您就可以将函数定义传递给函数
Ball b = () -> System.out.println("You hit it!");
上面的一行懒散地定义了Ball接口的hit()。请注意,这是惰性评估的。删除行b.hit()
您会注意到“you hit it!”根本无法在控制台中打印出来。
然而,这是一个幼稚的例子,您应该避免编写System.out.println()或简单地说函数代码中的副作用会污染您的环境。尽可能地发挥你的作用 Lambdas需要功能接口提供的目标类型,这就是为什么Lambdas与功能接口成对使用。
当lambda表达式出现在目标类型上下文中时,将自动创建实现函数接口的类实例
注意:接口类型应与lambda类型兼容
参考:-Lambdas需要功能接口提供的目标类型,这就是为什么Lambdas与功能接口成对使用。
当lambda表达式出现在目标类型上下文中时,将自动创建实现函数接口的类实例
注意:接口类型应与lambda类型兼容
参考资料:-谢谢您。。。因为这是一个函数接口System.out.println(“You hit!”)是hit()方法的实际实现,当调用b.hit时;它被执行了,谢谢你,阿什。。。因为这是一个函数接口System.out.println(“You hit!”)是hit()方法的实际实现,当调用b.hit时;它被执行。也许你想尝试而不是任意的web源?也许你想尝试而不是任意的web源?