Java supports anonymous classes and methods, which can form closures. Anonymous classes and methods are useful when you want to define a class or method inline without having to name it.
When you run this program, you’ll see the following output:
In this Java example, we use the Supplier<Integer> functional interface to create a closure. The intSeq method returns a Supplier<Integer> that increments and returns a counter each time it’s called.
The closure is created by the anonymous lambda expression that captures the i array. We use an array of size 1 instead of a simple int because Java requires variables used in lambda expressions to be effectively final.
In the main method, we demonstrate how the closure maintains its own state across multiple invocations, and how creating a new closure starts with a fresh state.
The last feature of methods we’ll look at for now is recursion.