Comparison of C Sharp and Java - Language and Features - Functional Programming - Closures

Closures

A closure is an inline function that captures variables from its lexical scope.

C# supports closures as anonymous methods or lambda expressions with full-featured closure semantics.

In Java, anonymous inner classes remains the preferred way to emulate closures. This is a more verbose construction.

This approach also has some differences compared to real closures, notably more controlled access to variables from the enclosing scopes: only final members can be referenced.

When a reference to a method can be passed around for later execution, a problem arises about what to do when the method has references to variables/parameters in its lexical scope. C# closures can access any variable/parameter from its lexical scope. In Java's anonymous inner classes, only references to final members of the lexical scope are allowed, thus requiring the developer to mark which variables to make available, and in what state (possibly requiring boxing).

While Java does not currently feature closures, it has been announced that some form of closures or lambdas will be included in JDK 8 that at latest update (10 October 2010) is scheduled for release "late 2012".

Read more about this topic:  Comparison Of C Sharp And Java, Language and Features, Functional Programming