Java Reference
In-Depth Information
Listing 5-18. A Printer Functional Interface
// Printer.java
package com.jdojo.lambda;
@FunctionalInterface
public interface Printer {
void print(String msg);
}
The program in Listing 5-19 creates two instances of the Printer interface: one using a lambda expression in the
getLambdaPrinter() method and one using an anonymous inner class in the getAnonymousPrinter() method. Both
instances use the keyword this inside the print() method. Both methods print the class name that the keyword this
refers to. The output shows that the keyword this has the same meaning inside the getLambdaPrinter() method and
the lambda expression.
Listing 5-19. Testing Scope of a Lambda Expression and an Anonymous Class
// ScopeTest.java
package com.jdojo.lambda;
public class ScopeTest {
public static void main(String[] args) {
ScopeTest test = new ScopeTest();
Printer lambdaPrinter = test.getLambdaPrinter();
lambdaPrinter.print("Lambda Expressions");
Printer anonymousPrinter = test.getAnonymousPrinter();
anonymousPrinter.print("Anonymous Class");
}
public Printer getLambdaPrinter() {
System.out.println("getLambdaPrinter(): " + this.getClass());
// Uses a lmabda expression
Printer printer = msg -> {
// Here, this refers to the current object of the
// ScopeTest class
System.out.println(msg + ": " + this.getClass());
};
return printer;
}
public Printer getAnonymousPrinter() {
System.out.println("getAnonymousPrinter(): " + this.getClass());
// Uses an anonymous class
Printer printer = new Printer() {
@Override
public void print(String msg) {
 
Search WWH ::




Custom Search