【发布时间】:2018-09-10 10:11:01
【问题描述】:
我已经看过并阅读了https://caveofprogramming.com/java/whats-new-in-java-8-lambda-expressions.html,并且我遵循了我为 runner 对象所做的相同模式,效果很好。
Runner runner = new Runner();
runner.run(() -> System.out.println("Print from Lambda expression"));
然后,我尝试创建一个简单的界面和类来应用我学到的东西。我只想用 lambda 表达式替换匿名类。我的理解是 lambda 表达式是匿名类的更短代码并提高可读性。
所以,我尝试启动另一个名为eucalyptus1 的实例并尝试@Override grow() 方法,但我的IDE 错误消息说:
com.smith.Eucalyptus中的grow()不能应用于(lambda expression)
谁能指出我在这里误解了什么?
代码如下:
// a simple interface
interface Plant {
public void grow();
}
// apply interface to class
class Eucalyptus implements Plant {
@Override
public void grow() {
System.out.println("This is from Eucalyptus");
}
}
public class Main {
public static void main(String[] args) {
// Create an instance of Eucalyptus
Eucalyptus eucalyptus = new Eucalyptus();
eucalyptus.grow();
// Anonymous class Myrtle from Plant interface
Plant myrtle = new Plant() {
@Override
public void grow() {
System.out.println("This was running from anonymous class from Plant Interface");
}
};
myrtle.grow();
// Try to create a lambda expression from Plant interface
// and override grow() method
// by print ("This was running from Lambda expression")
// this won't work. why?
Eucalyptus eucalyptus1 = new Eucalyptus();
eucalyptus1.grow(() -> System.out.println("This from Lambda expression"));
}
}
【问题讨论】:
标签: java lambda java-8 overriding functional-interface