Array of function pointers in Java

Java doesn't have a function pointer per se (or "delegate" in C# parlance). This sort of thing tends to be done with anonymous subclasses.

public interface Worker {
  void work();
}

class A {
  void foo() { System.out.println("A"); }
}

class B {
  void bar() { System.out.println("B"); }
}

A a = new A();
B b = new B();

Worker[] workers = new Worker[] {
  new Worker() { public void work() { a.foo(); } },
  new Worker() { public void work() { b.bar(); } }
};

for (Worker worker : workers) {
  worker.work();
}

You can achieve the same result with the functor pattern. For instance, having an abstract class:

abstract class Functor
{
  public abstract void execute();
}

Your "functions" would be in fact the execute method in the derived classes. Then you create an array of functors and populate it with the apropriated derived classes:

class DoSomething extends Functor
{
  public void execute()
  {
    System.out.println("blah blah blah");
  }
}

Functor [] myArray = new Functor[10];
myArray[5] = new DoSomething();

And then you can invoke:

myArray[5].execute();