我已经观看并阅读了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 错误消息说:
grow()incom.smith.Eucalyptus不能应用于(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"));
}
}
潇湘沐
长风秋雁
萧十郎
相关分类