Java Reference
In-Depth Information
36
37 // Create a scene and place it in the stage
38 Scene scene = new Scene(hBox, 300 , 50 );
39 primaryStage.setTitle( "LambdaHandlerDemo" ); // Set title
40 primaryStage.setScene(scene); // Place the scene in the stage
41 primaryStage.show(); // Display the stage
42 }
43 }
The program creates four handlers using lambda expressions (lines 23-35). Using lambda
expressions, the code is shorter and cleaner. As seen in this example, lambda expressions may
have many variations. Line 23 uses a declared type. Line 27 uses an inferred type since the
type can be determined by the compiler. Line 31 omits the parentheses for a single inferred
type. Line 35 omits the braces for a single statement in the body.
You can handle events by defining handler classes using inner classes, anonymous inner
classes, or lambda expressions. We recommend that you use lambda expressions because it
produces a shorter, clearer, and cleaner code.
inner class, anonymous class,
or Lambda?
15.11
What is a lambda expression? What is the benefit of using lambda expressions for
event handling? What is the syntax of a lambda expression?
Check
Point
15.12
What is a functional interface? Why is a functional interface required for a lambda
expression?
15.13
Show the output of the following code:
public class Test {
public static void main(String[] args) {
Test test = new Test();
test.setAction1(() -> System.out.print( "Action 1! " ));
test.setAction2(e -> System.out.print(e + " " ));
System.out.println(test.setAction3(e -> e * 2 ));
}
public void setAction1(T1 t) {
t.m();
}
public void setAction2(T2 t) {
t.m( 4.5 );
}
public double setAction3(T3 t) {
return t.m( 5.5 );
}
}
interface T1 {
public void m();
}
interface T2 {
public void m(Double d);
}
interface T3 {
public double m(Double d);
}
 
 
Search WWH ::




Custom Search