Callbacks are often very useful in C and C++, and Java is no exception to this.  However, the mechanism is different in Java.

In C/C++, it is quite common to call a function, passing an argument of type pointer to a second function, which the first function will call back at the appropriate time.

A C++ Callback Example

Imagine that you wish to write a function in C++ that goes through all the values in an array, and prints out all those values that match certain criteria, where the criteria are specified by calling back a supplied function.  The callback function is specified by passing in a pointer to that function.

Here’s some C++ code that supports this, using callback functions. 

#include <iostream>
using namespace std;

typedef void select(int value);

static void greaterThan10(int value)
{
    if (value > 10)
        cout << " " << value;
}

static void lessThan20(int value)
{
    if (value < 20)
        cout << " " << value;
}

static void forEach(int vals[], size_t elements, select *callMe)
{
    for (int i = 0; i < elements; i++)
    {
        callMe(vals[i]);
    }
}

int main()
{
    int values[] = { 4, -5, 8, 37, 56, 2, 15, 92 };
    cout << "Values > 10 : ";
    forEach(values, sizeof(values)/sizeof(values[0]), greaterThan10);
    cout << endl;

    cout << "Values < 20 : ";
    forEach(values, sizeof(values)/sizeof(values[0]), lessThan20);
    cout << endl;

    return 0;
}

The output of this program is:

Values > 10 :  37 56 15 92
Values < 20 :  4 -5 8 2 15

In other words, each of the values in the array that matches the condition enforced in each callback function.

A Java Callback Example

In Java, there are no pointers, far less pointers to functions.

Instead, we pass objects, not (pointers to) functions, and we typically use interfaces.

Here’s what it might look like in Java:

package examples;

public class CallbackExample
{
  public static void main(String[] args)
  {
    int[] values = { 4, -5, 8, 37, 56, 2, 15, 92 };
    System.out.print("Values > 10 : ");
    forEach(values, new GreaterThan10() );
    System.out.println();

    System.out.print("Values < 20 : ");
    forEach(values, new LessThan20() );
    System.out.println();
  }

  static void forEach(int[] vals, Callee callMe)
  {
    for (int i = 0; i < vals.length; i++)
    {
      callMe.select(vals[i]);
    }
  }
}

interface Callee
{
  void select(int value);
}

class GreaterThan10 implements Callee
{
  public void select(int value)
  {
    if (value > 10)
      System.out.print(" " + value);
  }
}

class LessThan20 implements Callee
{
  public void select(int value)
  {
    if (value < 20)
      System.out.print(" " + value);
  }
}

This outputs the following:

Values > 10 :  37 56 15 92
Values < 20 :  4 -5 8 2 15

which is identical output to that of the C++ program.