Java 8 Lambda表达式 - 嵌套类中的多个方法怎么样 [英] Java 8 Lambda Expressions - what about multiple methods in nested class
问题描述
我正在阅读以下新功能: http://www.javaworld.com/article/2078836/java-se/love-and-hate-for-java-8.html
I'm reading about the new features at: http://www.javaworld.com/article/2078836/java-se/love-and-hate-for-java-8.html
我看到了以下示例:
使用匿名类:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println("Action Detected");
}
});
使用Lambda:
button.addActionListener(e -> {
System.out.println("Action Detected");
});
如果 MouseListener
,有人会怎么做他们想在匿名类中实现多个方法,例如:
What would someone do with a MouseListener
if they wanted to implement multiple methods within the anonymous class, e.g.:
public void mousePressed(MouseEvent e) {
saySomething("Mouse pressed; # of clicks: "
+ e.getClickCount(), e);
}
public void mouseReleased(MouseEvent e) {
saySomething("Mouse released; # of clicks: "
+ e.getClickCount(), e);
}
......依此类推?
... and so on?
推荐答案
来自JLS 9.8
功能界面是一个界面只有一个抽象方法,因此
表示单个函数契约。
A functional interface is an interface that has just one abstract method, and thus represents a single function contract.
Lambdas需要这些功能接口因此受到限制他们的单一方法。匿名接口仍然需要用于实现多方法接口。
Lambdas require these functional interfaces so are restricted to their single method. Anonymous interfaces still need to be used for implementing multi-method interfaces.
addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
...
}
@Override
public void mousePressed(MouseEvent e) {
...
}
});
这篇关于Java 8 Lambda表达式 - 嵌套类中的多个方法怎么样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!