Pages

Sunday, December 30, 2012

Closure in Java using Anonymous Inner Class - example

Java doesn't support closure, but using Anonymous Inner Class, we can experience closure in Java.

Here is the code.
class Action {
	public void doAction() {
		System.out.println("Hello, world");
	}
}

class A {
	public void doStuff(Action a)
	{
		a.doAction();
	}
    public void method() {
        final int i = 0;

        doStuff(new Action() {
            public void doAction() {
                System.out.println(i);   // or whatever
            }
        });
    }
}

class Closure {
	public static void main(String[] args) {
		new A().method();
	}
}
You should be careful that the local variable in the method() method should be final in order to prevent this error message.

Closure.java:17: error: local variable i is accessed from within inner class; needs to be declared final System.out.println(i); // or whatever ^ 1 error

Instead of giving closure function to doStuff() method, anonymous inner class is given. In its implementation, doStuff() uses methods in A class as if it's closure functions. You can give different code block to doStuff() if necessary.

Compared to python example or lisp example, Java needs full support closure support to make the code simpler and easier to read.

References

1 comment:

  1. Fantastic example, interesting that it's similar to a closure. Also like this:

    Anonymous inner class example

    ReplyDelete