KeyListener Interface or KeyAdapter class?

Well … while reading to try to refresh my programming knowledge I am starting to have questions again.

By re-reading Kev’s coke and code tutorial I saw he used a private class extension of the KeyAdapter abstract class.While somewhere else I saw a class implementing the KeyListener interface.What is the difference?By checking the java doc I came to the conclusion that the only difference is that with KeyAdapter you can define whichever method you want , while with KeyListener you have to define all the abstract methods of the interface.

BUT … since I really want to learn corectly and since my personal conclusions more than often tend to be wrong , any clarifications here?What is the difference between those 2?

KeyAdapter is a utlity class which prevents you haveing to implement all the methods of KeyListener by implementing them for you with empty methods. You can then override what you want. The significant difference between the two is one is a class and on is an interface.

So, it’s a convienience thing. KeyAdapter can be used where you don’t mind using your one and only super class allowance on a utility to save time. Personally I generally always have inner/annonymous classes for keylisteners so use KeyAdapter rather alot.

Kev

First:
The Adapter class is some sort of convenience utility. If you are too “lazy” to implement the full interface… or if you just want to keep your code uncluttered, you use the Adapter class.

Second:
You don’t have multiple inheritance in java. A java class cannot extend more than one base class, but you can implement as most interfaces as you like. So if your class extends KeyAdapter, it cannot extend e.g. JPanel anymore. If on the other hand your class implements the KeyListener interface, it can extend whatever base class is needed.

As a rule of thumb:
You normally use adapter classes as anonymous inner classes, like


// add a anonymous utility class for handling inputs to "panel"
panel.addKeyListener(new KeyAdapter()
{
  // implement the method you need
});
// (...)

so you use the input functionality.

You use interfaces, if you want to create a new type of utility component, like


// This class is a transformation matrix to steer a starship
// based on mouse and keyboard input
class Steering extends Matrix implements MouseListener, MouseMotionListener, KeyboardListener
{
  public Steering(float minX,float maxX,float minY,float maxY)
  {
     // set up your steering algorithms based on the constructor parameters
  }

  // implement the different Listener interfaces to compute the transformation matrix
}
// (...)

so you extend the input functionality.

Hey big thanks to both of you.You tottaly covered my question.Thanks a lot :smiley: