A closure is an inner function that has access to the outer function even after the scope of outer function.This is a common programming concept in JavaScript, but we can achieve the same thing in java with the advent of JDK8 and functional programming.
here is a small java program which explains the closure concept in java,
/**
* This program explains the closure in java. This is achieved by using functional programming in JDK 8.
*/
package lambdas;
/**
* @author prabhu kvn
*
*/
public class LambdaClosureConcept {
public LambdaClosureConcept() {
}
public static void main(String[] args) {
LambdaClosureConcept obj = new LambdaClosureConcept();
obj.execute();
}
private void execute() {
LambdaClosure fn = getFunction();
System.out.println(fn.changeVal(10));
}
/**
* The "local" variable which got trapped in closure function.
*
* @return
*/
private LambdaClosure getFunction() {
int local = 89;
LambdaClosure fn = (int i) -> {
return i * local;
};
return fn;
}
}
// Functional interface
@FunctionalInterface
interface LambdaClosure {
int changeVal(int i);
}