無名クラスでクロージャの例


import java.util.*;

interface function<T> { public void func (T x); }

abstract class Foo { int n; abstract int foo(); }
class Bar extends Foo { Bar (int x) { n = x; } int foo() { return n + 1; } }
class Baz extends Foo { Baz (int x) { n = x; } int foo() { return n * 2; } }
class Main {
    public static void runClosure (function<Integer> f) {
        for (int i = 0; i < 1; i++) { f.func(i); }
    }
    public static void main (String args[]) {
        final Foo[] x = new Bar[]{ new Bar(0) };
        runClosure(new function<Integer>() {
            public void func(Integer n) {
                System.out.println(x[0].foo());
                x[0] = n % 2 == 0 ? new Bar(x[0].foo()) : new Baz(x[0].foo());
            }
        });
    }
}