A Java Callback Example
Home ] Up ] A C++ Callback Example ] [ 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.

 

This page was last modified on 02 October, 2007