Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Jan 12, 2004

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() {};
Matthew Johnson
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap