A callback is some code that you pass to a given method, so that it can be called at a later time.
In Java one obvious example is java.util.Comparator. You do not usually use a Comparator directly; rather, you pass it to some code that calls the Comparator at a later time:
Example:
class CodedString implements Comparable {
private int code;
private String text;
...
@Override
public boolean equals() {
// member-wise equality
}
@Override
public int hashCode() {
// member-wise equality
}
@Override
public boolean compareTo(CodedString cs) {
// Compare using "code" first, then
// "text" if both codes are equal.
}
}
...
public void sortCodedStringsByText(List codedStrings) {
Comparator comparatorByText = new Comparator() {
@Override
public int compare(CodedString cs1, CodedString cs2) {
// Compare cs1 and cs2 using just the "text" field
}
}
// Here we pass the comparatorByText callback to Collections.sort(...)
// Collections.sort(...) will then call this callback whenever it
// needs to compare two items from the list being sorted.
// As a result, we will get the list sorted by just the "text" field.
// If we do not pass a callback, Collections.sort will use the default
// comparison for the class (first by "code", then by "text").
Collections.sort(codedStrings, comparatorByText);
}