Java Reference
In-Depth Information
The anonymous inner classes in this example are compiled into
AnonymousHandlerDemo$1.class
,
AnonymousHandlerDemo$2.class
,
AnonymousHandlerDemo$3.class
, and
AnonymousHandlerDemo$4.class
.
15.9
✓
✓
If class
A
is an inner class in class
B
, what is the .class file for
A
? If class
B
contains
two anonymous inner classes, what are the .class file names for these two classes?
Check
Point
15.10
What is wrong in the following code?
public class
Test
extends
Application {
public void
start(Stage stage) {
Button btOK =
new
Button(
"OK"
);
}
public class
Test
extends
Application {
public void
start(Stage stage) {
Button btOK =
new
Button(
"OK"
);
btOK.setOnAction(
new
EventHandler<ActionEvent> {
public void
handle
(ActionEvent e) {
System.out.println
(e.getSource());
}
}
// Something missing here
}
}
private class
Handler
implements
EventHandler<ActionEvent> {
public void
handle(Action e) {
System.out.println(e.getSource());
}
}
}
(a)
(b)
Expressions
Lambda expressions can be used to greatly simplify coding for event handling.
Key
Point
Lambda expression
is a new feature in Java 8. Lambda expressions can be viewed as an
anonymous class with a concise syntax. For example, the following code in (a) can be greatly
simplified using a lambda expression in (b) in three lines.
lambda expression
btEnlarge.setOnAction(e -> {
// Code for processing event e
});
btEnlarge.setOnAction(
new
EventHandler<ActionEvent>() {
@Override
public void
handle(ActionEvent e) {
// Code for processing event e
}
}
});
(a) Anonymous inner class event handler
(b) Lambda expression event handler
The basic syntax for a lambda expression is either
(type1 param1, type2 param2, ...) -> expression
or
(type1 param1, type2 param2, ...) -> { statements; }
Search WWH ::
Custom Search