Java8: Closures
In the below code Calculator class implementation will have access to b variable even its not in the scope. This is done by java compiler having a copy of b variable and sending to the calculator class.
int a=10;
int b=20;
operate(a, new Calculator() {
@Override
public void process(int i) {
System.out.println(i + " - " + b);
}
});
What if you try change this value of be
int a=10;
int b=20;
operate(a, new Calculator() {
b=2;
@Override
public void process(int i) {
System.out.println(i + " - " + b);
}
});
You will get the following error.
Variable used in lambda expression should be final or effectively final
Before Java 8 you must declare the variable b as a final and from java 8 you can use it without changing the variable. If you try to change you will see above error.
Read my other blogs: