2

I am making a framework for making fractals in processing, however, I need to use functions as parameters for a constructor of a class. Something like:

class Fractal {
   String name;
   void initialize;
   Fractal(String Name, void setup) {
      ...
   }
}
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
Nikos
  • 57
  • 1
  • 7

1 Answers1

1

I'm going to guess you're coming from a JavaScript background?

Traditionally, Java didn't really have a way to do this. Instead you'd pass an anonymous instance of an interface, like this:

interface Runner{
   public void run();
}

class Fractal {
   String name;
   Runner initialize;
   Fractal(String name, Runner setup) {
      ...
   }
}

Runner r = new Runner(){
   public void run(){
      // whatever
   }
}

Fractal fractal = new Fractal("name here", r);

Note that Java provides a Runnable interface that you can use instead of creating your own, but I wanted to spell it out here to make it more obvious.

As of Java 8, you can pass a reference to a function as a parameter. This is called a lambda function. Googling "Java lambda function" will return a ton of results.

From this answer:

public void pass() {
    run(()-> System.out.println("Hello world"));
}

public void run(Runnable function) {
    function.run();
}

Depending on how you're using Processing, you might be stuck with the first approach though, since I don't think the Processing editor supports Java 8 yet.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107