Java Closures

There was no tidy way to implement a closure in a Java program until Java support for inner classes was added in Java 1.1.

Closure Structure

The structure of a closure in the Java language is shown in Example 9-1.

Example 9-1. Java closure
public class ClosureExample1 {
    int remote = 0;
    OtherClass c = new OtherClass();

    public void bar(){
        c.foo(new BazClass() {
            public void doIt(){
                remote += 1;
                local = remote; //  local is in BazClass
            }
        });
    }

    static void main(String args[]){
        (new ClosureExample1()).bar();
    }
}

The bar method creates an instance of an anonymous local inner class and passes that object to the foo method. When the foo method uses the object by calling baz.doIt, the doIt method executes in the environment of the bar

Get Real-Time Java™ Platform Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.