Simple code examples of closures in Java

  • 2020-12-19 21:01:17
  • OfStack

1. Definition of closure.

There are a lot of different people who have defined closures, and here is a collection of a few.

# is a function that references a free variable. This function is usually defined in another external function and references a variable in the external function. -- < < wikipedia > >

# is a callable object that records information from the scope in which it was created. -- < < Java programming ideas > >

# is an anonymous block of code that can take a parameter and return a return value, or can refer to and use variables defined in the visible field around it. - Groovy [' � ru: vi]

# is an expression that has free variables and the context in which these variables are bound.

# closures allow you to encapsulate 1 behavior, pass it around like an object, and still have access to the context in which it was first declared.

# is an expression (usually a function) that has multiple variables and the environment to which those variables are bound, and therefore the variables are also a part of the expression.

# Closures are blocks of code that can contain free (unbound) variables; These variables are not defined in the code block or in any global context, but in the context in which the code block is defined.

2. Simple examples of closures:


package Test;
public class Test {
	private int data=0;
	private class Inner{
		void print()
		  {
			System.out.println(Test.this.data);
		}
	}
	Inner getInnerInstance()
	 {
		return new Inner();
	}
	/**
 * @param args
 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Test t1=new Test();
		t1.data=1;
		Test t2=new Test();
		t2.data=2;
		Inner inner1=t1.getInnerInstance();
		Inner inner2=t2.getInnerInstance();
		inner1.print();
		//1
		inner2.print();
		//2
	}
}

conclusion

That's it for this article about simple code examples of closures in Java, and I hope you found them helpful. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: