Tuesday, January 17, 2012

Call back functions

A callback method is one which is passed as an argument from another method which is invoked due to some kind of event. The 'call back' nature of the argument is that it returns it's result to the method that provided it as an argument - that is to say that it 'calls back' with the return value of the callback method.//An innocuous looking method which will become known as a callback method
//because of the way in which we will invoke it.
int meaningOfLife(void) {
return 42;
}
//An innocuous looking method which just takes an int and prints it to screen
void Print_A_Number(int a_Number) {
System.out.print(a_Number);
}
//invoking a method which passes another method as an argument in reaction to an event (the 'another' method - meaningOfLife - is therefore called a callback method) and the event - main() - is that the program is starting
void main() {
Print_A_Number(meaningOfLife);
}
Callbacks are so-called due to their usage with pointer languages. If you don't use one of those, don't labour over the name 'callback'. Just understand that it is just a name to describe a method that's supplied as an argument to another method, such that when that method is called (whatever condition, such as a button click, a timer tick etc) the callback method is therefore invoked, which returns a result to the calling method, which in turn returns a result to the event.

No comments:

Post a Comment