What is the difference between listeners and adapters?

后端 未结 5 441
再見小時候
再見小時候 2021-02-02 11:07

I\'m trying to differentiate between listeners and adapters.

Are they pretty much the same but in listeners you have to implement all the methods in the interface, but w

5条回答
  •  广开言路
    2021-02-02 12:04

    You can do everything with either, but if you start with the interface, your code is going to have a LOT of boilerplate. I'm sure you noticed that when you tried it out. That statement about instantiation etc. is a quite convoluted way of saying it and there's a lot of confusion of terms. You can write

    c.addWindowListener(new WindowListener() {
      @Override public void windowActivated(WindowEvent arg0) { }
      @Override public void windowClosed(WindowEvent arg0) { System.exit(0); }
      @Override public void windowClosing(WindowEvent arg0) { }
      @Override public void windowDeactivated(WindowEvent arg0) { }
      @Override public void windowDeiconified(WindowEvent arg0) { }
      @Override public void windowIconified(WindowEvent arg0) { }
      @Override public void windowOpened(WindowEvent arg0) { }
    });
    

    or you can write

    c.addWindowListener(new WindowAdapter() {
      @Override public void windowClosed(WindowEvent arg0) { System.exit(0); }
    });
    

    In neither case are you instantiating either WindowListener or WindowAdapter—you are creating anonymous classes that implement WindowListener/extend WindowAdapter. But when you implement the interface directly, you are forced to implement all methods, wheras when you extend the adapter class, you can only override what you need. That class already has exactly these empty implementations that you had to write in the Listener case.

提交回复
热议问题