Reputation: 16117
I have this code here. (this code was taken from Thinking in Java 4th Edition)
//{Args: "D.*\.java}
import java.util.regex.*;
import java.io.*;
import java.util.*;
public class DirList {
public static void main (String[] args){
File path = new File(".");
String[] list;
if(args.length == 0)
list = path.list();
else
list = path.list(new DirFilter(args[0]));
Arrays.sort(list,String.CASE_INSENSITIVE_ORDER);
for(String dirItem : list ){
System.out.println(dirItem);
}
}
}
class DirFilter implements FilenameFilter{
private Pattern pattern;
public DirFilter(String regex){
pattern = Pattern.compile(regex);
}
public boolean accept(File Dir,String name){
return pattern.matcher(name).matches();
}
}
And then as I read its explanation I have encountered this
DirFilter
’s sole reason for existence is to provide theaccept( )
method to thelist( )
method so thatlist( )
can "call back"accept( )
to determine which file names should be included in the list. Thus, this structure is often referred to as a callback.
Soo what is specifically a callback?
Upvotes: 0
Views: 377
Reputation: 1760
In the context of Java, method implemented for an interface will be considered as callback. In your code, DirFilter
implements FilenameFilter
which has accept method. Since we are passing an instance of DirFilter
to list method, this method can call accept method though unaware of its implementation.
Upvotes: 0
Reputation: 150108
A callback is a method that you provide to a library that you are using so that the library can call your method to perform work (or rather call back to your code, thus the name).
More generally, any two layers of code can interact through a callback function.
Upvotes: 4
Reputation: 4842
A callback is really just a function that you hand over to some API, which is then called by the API on some expected events. For example, if you are using some networking API, then it's possible for you to make an asynchronous send request along with a callback that will be called once the send request is complete. You can use that callback to set some boolean value to let you know that you can now send something else if/when you have anything new to send.
Upvotes: 0