2.6 Implementing Interfaces
In Groovy we can morph a map or a block of code into interfaces, which lets us implement interfaces with multiple methods quickly. In this section, you’ll see a Java way of implementing interfaces, and then you’ll learn how to take advantage of Groovy’s facilities.
Here’s the all-too-familiar Java code to register an event handler to a Swing JButton.
The call to
addActionListener
expects an instance that implements the ActionListener
interface. We create an anonymous inner class that implements ActionListener, and we provide the required
actionPerformed
method. This method insists on taking
ActionEvent as an argument even though we have no use for it in this
example.
| | // Java code |
| | button.addActionListener( ... |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access