devxlogo

Force the Extension of a Class Without Overriding Any Single Method

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() {};
See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist