0

Possible Duplicate:
How to pass a function as a parameter in Java?

How can i give a function as parameter?

for example:

for(Confetti c : confetti) {
   b.draw(someFunction(){strokeWeight(random(10));
}

where in the confetti class there would be something like

draw(void myFunc){
   for(int i = 0; i < 10; i++) {
    myFunc(); // run it
    ellipse(50, 50, 5, 5);
   }
}
Community
  • 1
  • 1
clankill3r
  • 9,146
  • 20
  • 70
  • 126

1 Answers1

2

You can't. Java does not treat functions as first class objects. What you can do is define an interface with a method that contains the function you want called.

interface Confetti {
   public void draw();
}

class DrawRandomStroke implements Confetti {
 public void draw() {
      strokeWeight(random(10));
}

And then pass your DrawRandomStroke objects to your method. If you want to use a language that supports what you're trying to do and still be in the java world, look at groovy or scala.

Rick Mangi
  • 3,761
  • 1
  • 14
  • 17