0

Possible Duplicate:
How are Anonymous (inner) classes used in Java?

I just discovered the following feature while reading through Java Puzzlers

public class Main {
    public static void main(String[] args) {
        new Object() {
            void helloWorld() {
                System.out.println("Hello world!");
            }
        }.helloWorld();
    }
}

And I find this amazingly handy. Very closure-like. The problem is that I can't find any information on this construct. Can anyone provide me with a link describing this feature?

Community
  • 1
  • 1

3 Answers3

3

This is an example of an anonymous inner class. It has been supported since Java 1.1.

This might appear to be closure like, but in fact there are limitations1 that make it less than true closures. However, despite these limitations, anonymous inner classes are still very useful ... and widely used in Swing and similar frameworks which require lightweight callbacks.

References:


1 - The reason that an anonymous inner class (or a named inner class) doesn't act like a true closure, is that it is not allowed to refer to mutable local variables in an enclosing scope. You can refer to an instance variable or a final local variable, but naming a non-final local variable (or method parameter variable) is a compilation error.

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
2
new Object() {
    void helloWorld() {
        System.out.println("Hello world!");
    }
}.helloWorld();

This means, create an instance of an anonym class that extends Object and than call the method .helloWorld() on it.

MrSmith42
  • 9,961
  • 6
  • 38
  • 49
0

Java Specification 15.9.5. Anonymous Class Declarations and 15.9.5.1. Anonymous Constructors http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.5