1. Definition of closure.
There are many different people who have defined closures, and here are some.
# is a function that references free variables. This function is usually defined in another external function and refers to variables in the external function. -- <<wikipedia>>
# is a callable object that records some information from the scope in which it was created. -- <<Java Programming Thoughts>>
# is an anonymous code block that can accept parameters and return a return value, or reference and use variables defined in the visible domain around it. -- Groovy ['ru:vi]
# is an expression that has the context of free variables and the bonding of these variables.
# Closure allows you to encapsulate some behaviors, pass them around like an object, and it can still access the context of the original first declaration.
# refers to an expression (usually a function) that has multiple variables and an environment bound to these variables, so these variables are also part of the expression.
# Closures are code blocks that can contain free (unbound) variables; these variables are not defined in this code block or any global context, but in the environment where the code block is defined.
2. Simple example of closure:
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 stubTest t1=new Test();t1.data=1;Test t2=new Test();t2.data=2;Inner inner1=t1.getInnerInstance();Inner inner2=t2.getInnerInstance();inner1.print();//1inner2.print();//2}}Summarize
The above is all about the simple code example of closures in Java. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!