Simple code example for closures in Java and java code example
1. Closure definition.
There are many different people who have defined the closure, and some of them are collected here.
# Is a function that references free variables. This function is usually defined in another external function and referenced variables in the external function. -- <Wikipedia>
# Is a callable object, which records some information, which comes from the scope of its creation. -- <Java programming ideology>
# Is an anonymous code block. It can accept parameters and return a return value. It can also be referenced and used around it to see the variables defined in the domain. -- Groovy ['invalid ru: vi]
# Is an expression that has the Context Environment of free variables and those variables.
# The closure allows you to encapsulate some actions and deliver them like an object, and it can still access the context of the first declaration.
# It refers to the expressions (usually a function) that have multiple variables and the Environment bound to these variables. Therefore, these variables are also part of the expressions.
# 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.
Ii. Simple closure example:
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}}
Summary
The above is all about the simple code example of closures in Java. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!