Java Reference
In-Depth Information
2.3.2. Fifth attempt: using an anonymous class
The following code shows how to rewrite the filtering example by creating an object that
implements ApplePredicate using an anonymous class:
Anonymous classes are often used in the context of GUI applications to create event-handler
objects (here using the JavaFX API, a modern UI platform for Java):
button.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
System.out.println("Woooo a click!!");
}
});
But anonymous classes are still not good enough. First, they tend to be very bulky because they
take a lot of space, as shown in the highlighted code here using the same two examples used
previously:
Second, many programmers find them confusing to use. For example, Quiz 2.2 shows a classic
Java puzzler that catches most programmers off guard! Try your hand at it.
Quiz 2.2: Anonymous class puzzler
What will the output be when this code is executed: 4, 5, 6, or 42?
Search WWH ::




Custom Search