Haydos
Haydos

Reputation: 422

Error implementing interface as anonymous inner class

I'm learning JavaFX using Intellij IDEA. When compiling the following code:

public class Main extends Application implements EventHandler<ActionEvent>{

//More code 

    button.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            System.out.println("Hello World");
        }

//More code

    });

I get the error message "Class must either be declared abstract or implement abstract method". But by observation of the code, I am clearly implementing the functional interface using an anonymous inner class.

When I construct an empty handle method inside the Main class, the code works fine, but I don't believe I should have to. What is going on!

Upvotes: 2

Views: 215

Answers (1)

Simon Forsberg
Simon Forsberg

Reputation: 13331

The reason is this line:

public class Main extends Application implements EventHandler<ActionEvent>{

Remove the implements EventHandler<ActionEvent> and you're good.

You are probably confused because you have made both your Main class implement the interface, and you are creating an anonymous inner class that also implements the interface. This leaves you with one class that has implemented the method - the anonymous inner class. But the outer Main class has not implemented the method, which is why you get the error message.

Upvotes: 5

Related Questions