在Java中实现接口并覆盖方法? [英] Implement an interface and override methods in Java?
问题描述
为什么必须重写接口的所有方法?
Why do you have to override all methods of an interface?
例如,如果我有
public class Foo extend JFrame implements ActionListener, KeyListener {
foo(){
}
@Override
public void keyPressed(KeyEvent arg) {
}
@Override
public void keyReleased(KeyEvent arg) {
}
@Override
public void keyTyped(KeyEvent arg) {
}
}
我将有很多我什至不会使用的方法,有没有一种方法可以删除未使用的已实现方法,例如,如果我计划从界面中使用一种方法
I'm going to have lots of methods I won't even be using, is there a way to remove the un used implemented methods, for instance if i plan to use one method from the interface
我也不想使用抽象,因为这意味着我无法创建对象的实例(至少我的编译器这样说)
I don't want to use abstract either, as this means I can't create an instance of the object (at least my compiler says so)
推荐答案
具体类必须始终实现接口的所有方法.如果尚未扩展JFrame
,则可以扩展KeyAdapter
.它为KeyListener
实现了空方法,以避免将其写出.您可以在Foo
类内部使用匿名类,如下所示:
Concrete classes must always implement all of the methods of an interface. If you weren't already extending JFrame
you could extend KeyAdapter
. It implements empty methods for KeyListener
to avoid writing them out. You could use an anonymous class with that inside of your Foo
class like this:
addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
// handle typed key here
}
});
这篇关于在Java中实现接口并覆盖方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!