Java Reference
In-Depth Information
argument. Recall that for Map s, the first parameter represents the key and the second rep-
resents the corresponding value. The lambda in lines 21-22 uses parameter face as the key
and frequency as the value, and displays the face and frequency.
17.9 Lambda Event Handlers
In Section 12.11, you learned how to implement an event handler using an anonymous
inner class. Some event-listener interfaces—such as ActionListener and ItemListener
are functional interfaces. For such interfaces, you can implement event handlers with
lambdas. For example, the following statement from Fig. 12.21:
imagesJComboBox.addItemListener(
new ItemListener() // anonymous inner class
{
// handle JComboBox event
@Override
public void itemStateChanged(ItemEvent event)
{
// determine whether item selected
if (event.getStateChange() == ItemEvent.SELECTED )
label.setIcon(icons[
imagesJComboBox.getSelectedIndex()]);
}
} // end anonymous inner class
); // end call to addItemListener
which registers an event handler for a JComboBox can be implemented more concisely as
imagesJComboBox.addItemListener(event -> {
if (event.getStateChange() == ItemEvent.SELECTED )
label.setIcon(icons[imagesJComboBox.getSelectedIndex()]);
});
For a simple event handler like this one, a lambda significantly reduces the amount of code
you need to write.
17.10 Additional Notes on Java SE 8 Interfaces
Java SE 8 Interfaces Allow Inheritance of Method Implementations
Functional interfaces must contain only one abstract method, but may also contain
default methods and static methods that are fully implemented in the interface decla-
rations. For example, the Function interface—which is used extensively in functional pro-
gramming—has methods apply ( abstract ), compose ( default ), andThen ( default ) and
identity ( static ).
When a class implements an interface with default methods and does not override
them, the class inherits the default methods' implementations. An interface's designer
can now evolve an interface by adding new default and static methods without
breaking existing code that implements the interface. For example, interface Comparator
(Section 16.7.1) now contains many default and static methods, but older classes that
implement this interface will still compile and operate properly in Java SE 8.
If one class inherits the same default method from two unrelated interfaces, the class
must override that method; otherwise, the compiler will not know which method to use,
so it will generate a compilation error.
 
 
 
Search WWH ::




Custom Search