Is there any other way in java to implement call backs apart from inner classes? What is the difference between callbacks and closures?
a callback is executable code that is passed as an argument to other code. a closure is a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these variables.
Callbacks are also closures as the passed function is executed inside other function just as if the callback were defined in the containing function.
A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
Closure is how you build it, callback is how you use it.
A callback can be implemented as a closure (in languages that have them) or an implementation of an interface (in Java, as an anonymous inner class or a regular class).
Callback means that you pass a piece of code to a function, so that the function can call that piece of code later. It is a special kind of parameter.
The piece of code can be a function pointer or a closure or an object with well-known methods, depending on what the language offers.
Both closures and anonymous inner classes (and others) can be used as callbacks. A callback is just some code which is passed as an argument to other code.
A big difference of closures, compared to Java's anonymous inner classes, is that (in imperative languages) a closure can modify the variables of the surrounding scope. Wikipedia gives the following example:
var f, g;
function foo() {
var x = 0;
f = function() { return ++x; };
g = function() { return --x; };
x = 1;
alert('inside foo, call to f(): ' + f()); // "2"
}
foo();
alert('call to g(): ' + g()); // "1"
alert('call to f(): ' + f()); // "2"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With