Quick question about Hello Input System and java

  private ActionListener actionListener = new ActionListener() {
    public void onAction(String name, boolean keyPressed, float tpf) {

Hello, I’m new to java and my understanding of the differences between Classes, Objects, and Methods aren’t 100% yet. Is the above code an object with an embedded method? or more specifically why and how do you follow the declaration with braces? Thing thing = new Thing() { //stuff };

I learned from book/internet and had my mind blown when I saw this. I had no idea you could write the behavior of a method for an object as you initialized it.

As far as I know its called an Anonymous inner class… or something (not sure). Used lots for listeners so you can write how you respond to events easily. I first saw them used when someone created a bunch of GUI Buttons, they declared what each button did when pressed upon creating the button objects.

If that name is wrong I’m sure someone here will be able to tell us though.

That looks like it!

Yeah, I guess its used to allow users to define methods, very useful for IO!

Yeah, it’s an anonymous inner class. Essentially it’s defining a subclass of ActionListener on the fly… so you can override methods right there. It’s “anonymous” because the new class doesn’t have a real name.

If you were to print the class of that object it would look something like: MyOuterClass$1 as the class name (if that was inside a class called MyOuterClass).

So and now we continue with lamdas !


Runnable r1 = new Runnable(){
       public void run(){
         System.out.println("Hello world one!");

And with lambdas:

Runnable r2 = () -> System.out.println("Hello world two!");

I want to add a note since it’s still related to anonymous classes and it is something not really common that you will probably encounter in jme because some core libraries use it extensively (eg Nifty Gui).

I’m talking about this double brackets thing:

SomeClass c=new SomeClass(){{
    // Code

that is just a condensed version of

SomeClass c=new SomeClass(){
    // Code

The inner brackets contain what is called an initialization block (whose static { … } variant is more common ).

Its purpose is to be used for ‘advanced’ field initializations (for example if you have to deal with exceptions) and it can be used in both anonymous and non-anonymous classes even though it behaves differently: when used in anonymous classes (like the code above) it’s executed after the constructor, while in non-anonymous classes it is executed before the constructor.

So virtually what it does in anonymous classes is appending code at the end of the constructor.

That’s cool! Lamdas seem like the way to go when implementing simple ‘Single Abstract Methods’ that use only a couple lines.