Force the Extension of a Class Without Overriding Any Single Method

With some classes, it doesn’t make sense to instantiate the class itself but overriding of any of its methods will result in a usable class. This is the case for the various AWT adapter classes (which complement the listener classes), such as KeyAdapter.

If you implement the KeyListener interface, you must implement all three of its methods: keyPressed, keyReleased, and keyTyped. If you don’t need all three methods, it’s easier to simply extend KeyAdapter and implement only the methods you need.

You don’t need to override any one method of KeyAdapter, yet KeyAdapter itself cannot be initialized. How does this work? KeyAdapter is an abstract class, but none of its methods is abstract (each has an empty implementation). You’re cajoled, in practice, to override at least one of the methods:

KeyAdapter ka = new KeyAdapter() {  public void keyPressed(KeyEvent e) {    System.out.println("Key pressed!");  }};

In fact, though, you aren’t forced to override anything! The following will compile as well:

KeyAdapter ka = new KeyAdapter() {};
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: