Java Reference
In-Depth Information
The data type for a parameter may be explicitly declared or implicitly inferred by the com-
piler. The parentheses can be omitted if there is only one parameter without an explicit data
type. In the preceding example, the lambda expression is as follows
e -> {
// Code for processing event e
}
The compiler treats a lambda expression as if it is an object created from an anonymous
inner class. In this case, the compiler understands that the object must be an instance of
EventHandler<ActionEvent>
. Since the
EventHandler
interface defines the
handle
method with a parameter of the
ActionEvent
type, the compiler automatically recognizes
that
e
is a parameter of the
ActionEvent
type, and the statements are for the body of the
handle
method. The
EventHandler
interface contains just one method. The statements
in the lambda expression are all for that method. If it contains multiple methods, the com-
piler will not be able to compile the lambda expression. So, for the compiler to understand
lambda expressions, the interface must contain exactly one abstract method. Such an interface
is known as a
functional interface
or a
Single Abstract Method
(SAM) interface.
ListingĀ 15.4 can be simplified using lambda expressions as shown in ListingĀ 15.5.
functional interface
SAM interface
L
ISTING
15.5
LambdaHandlerDemo.java
1
import
javafx.application.Application;
2
import
javafx.event.ActionEvent;
3
import
javafx.geometry.Pos;
4
import
javafx.scene.Scene;
5
import
javafx.scene.control.Button;
6
import
javafx.scene.layout.HBox;
7
import
javafx.stage.Stage;
8
9
public class
LambdaHandlerDemo
extends
Application {
10 @Override
// Override the start method in the Application class
11
public void
start(Stage primaryStage) {
12
// Hold two buttons in an HBox
13 HBox hBox =
new
HBox();
14 hBox.setSpacing(
10
);
15 hBox.setAlignment(Pos.CENTER);
16 Button btNew =
new
Button(
"New"
);
17 Button btOpen =
new
Button(
"Open"
);
18 Button btSave =
new
Button(
"Save"
);
19 Button btPrint =
new
Button(
"Print"
);
20 hBox.getChildren().addAll(btNew, btOpen, btSave, btPrint);
21
22
// Create and register the handler
23 btNew.setOnAction((ActionEvent e) -> {
24 System.out.println(
"Process New"
);
25 });
26
27 btOpen.setOnAction((e) -> {
28 System.out.println(
"Process Open"
);
29 });
30
31 btSave.setOnAction(e -> {
32 System.out.println(
"Process Save"
);
33 });
34
35 btPrint.setOnAction(e -> System.out.println(
"Process Print"
));
lambda handler
lambda handler
lambda handler
lambda handler
Search WWH ::
Custom Search