Manitoba Manitoba - 2 months ago 12
Java Question

How to make a method a parameter for a constructor

While making a small game in Java, I stumbled upon the keyListener class, which asks for three methods when instanced (keyTyped, keyPressed, and keyReleased), as below:

JFrame.addKeyListener(new KeyListener(){
public void keyTyped(KeyEvent evnt) {
//blah
}
public void keyPressed(KeyEvent evnt) {
//blah
}
public void keyReleased(KeyEvent evnt) {
//blah
}
});


How can I get a class I am making on my own accept methods as a parameter as above?

Answer

new KeyListener() { ... } actually creates an anonymous inner class that implements KeyListener. As such it can access any visible field of the class that created it as well as any local final variable inside the method that called the constructor.

Example:

class Outer {
  int x;

  void initUI( final int z) {
    final int y = 0;        
    int nope = 1; //you can't access this since it is neither final nor a field like x

    JFrame.addKeyListener( new KeyListener() {
      public void keyTyped(KeyEvent evnt) {
        System.out.println( x + y + z ); //you can access all of them
      }
    });
  }
}

If you want to provide a constructor for your key listener you'll need to explicitly define a class, as anonymous classes can't have custom constructors. That means you'd have to do something like this (attention: pseudo code):

class Outer {
  void initUI() {
    JFrame.addKeyListener( new InnerKeyListener( myParam ) );
  }

  class InnerKeyListener implements KeyListener {
    InnerKeyListener( Param p ) {
    }

    ...
  }
}

Of course you can put the inner class into a separe file as well or make it a static inner class.

Comments