Implement an interface and override methods in Java?

后端 未结 6 1031
旧巷少年郎
旧巷少年郎 2021-01-24 16:14

Why do you have to override all methods of an interface?

For instance if I have

public class Foo extend JFrame implements ActionListener, KeyListener {
          


        
6条回答
  •  日久生厌
    2021-01-24 16:26

    This is exactly what the KeyAdapter class is for: it implements all methods of the interface (but none of the implementations do anything). Since you cannot extend two classes, you should use an inner class for your listener (which is a cleaner design anyway):

    public class Foo extend JFrame {
          foo(){
              ...
              component.addKeyListener(new MyKeyListener());
              ...
          }
    
        private class MyKeyListener extends KeyAdapter{
            @Override
            public void keyPressed(KeyEvent arg) {          
            }
        }
    }
    

提交回复
热议问题