1

Where would I implement the following code? By where I mean do I make a new class? Put it in the constructor of my main class? etc.

public interface ActionListener extends EventListener {
void actionPerformed(ActionEvent e);
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
zmi
  • 11
  • 3

2 Answers2

1

You need to make a class that implements the interface.

public class ActionListenerExample implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        // Do something here
    }

}

You can then make an object of the class.

ActionListenerExample listener = new ActionListenerExample();

With Java 8, you could make this more compact by using a lambda expression.

ActionListener listener = action -> {
    // Do something
};

If you don't use Java 8 (which you should) but still want to make it compact, use an anonymous class.

ActionListener listener = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // Do something here
    }
}
SamTebbs33
  • 5,507
  • 3
  • 22
  • 44
  • so what does interface mean? – zmi Mar 15 '16 at 23:23
  • @zmi An interface is a type (essentially an abstract class) that provides a blueprint of methods that a class then needs to implement. An interface provides the abstraction of the behaviour while the implementing class provides the implementation of the behaviour. – SamTebbs33 Mar 15 '16 at 23:25
  • 1
    @zmi [What are interfaces](https://docs.oracle.com/javase/tutorial/java/concepts/interface.html) – MadProgrammer Mar 15 '16 at 23:29
0

Here's an example implemented as a local variable:

  final ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
          System.out.println("Hello World");
      }};