Closure in Java 6

There is a way to encapsulate variable’s value into definition another method. Of course, it is far less flexible than “real” closure, like that one in JavaScript… but in my humble opinion it is still closure!
Keyword final and new inner class are required:

public static void main(String []  args) {

	final String SECRET = "HELLO CLOSURE";

	class InnerSecretClass{

		public String getSecret(){
			return SECRET;

	System.out.println(new InnerSecretClass().getSecret());

This entry was posted in Java. Bookmark the permalink.

2 Responses to Closure in Java 6

  1. Lambda expression allows the compiler to infer the type of the variable based on the context

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>