0

Whenever I need to grab input from the keyboard, I use the following KeyAdapter inner class technique.

controls = new KeyAdapter()
   {
       public void keyPressed(KeyEvent e)
          {
              //do something with input
          }
   };

It wasn't recently that I learned how to do this, but I am beginning to become uncomfortable, as I like to understand what is happening in my code. What exactly is Java doing here? The best I can come up with is it is a form of inner class, but why can't I write a constructor?

syb0rg
  • 8,057
  • 9
  • 41
  • 81
  • 1
    Search for "Java *anonymous* class", and read the [Anonymous Classes trail](http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html). Knowing the name helps a bunch. Also related is an "initialization block" or [Double Brace Initialization](http://c2.com/cgi/wiki?DoubleBraceInitialization) which can be used to simulate (fsvo) a constructor here. The last question is the most interesting (i.e. it's not trivially explained in tutorials), but is buried: "Why can't anonymous classes have a constructor?" – user2246674 May 25 '13 at 21:54
  • check this issue: http://stackoverflow.com/questions/5107158/how-to-pass-parameters-to-anonymous-class – Deividi Cavarzan May 25 '13 at 21:58
  • 1
    And even "Why can't anonymous classes have a constructor?" is [already answered](http://stackoverflow.com/a/362443/2246674). A little bit of reading/research can go a long way. – user2246674 May 25 '13 at 22:00
  • See also this [Q&A](http://stackoverflow.com/q/1673841/230513) on the [_null implementation pattern_](http://en.wikipedia.org/wiki/Null_Object_pattern). – trashgod May 25 '13 at 22:52

0 Answers0