Best method for storing and calling function as variable?

edited January 2016 in How To...

I just created a Button class for my current project, and I'd like a way to assign a function to each button created.

It would be most useful to store the function as a variable upon calling the constructor and later call that function when a click is detected inside the Button. After searching the forums I see it's rather difficult to do this, and it's also a bad idea to store the function name as a String and use that to call it.

I'd like to avoid hard coding the functions for each button into a clickHandler function. Do you guys have suggestions on what to do?



  • This is clever, thanks

  • Quick question, in your solution, why is it necessary for action() to be abstract? Can you only override abstract methods?

  • edited January 2016
    • Keyword abstract is just something fancy which obliges us to implement all methods marked as such when we try to instantiate or extend its class.
    • An abstract class is an incomplete class. That is, it can have incomplete abstract methods.
    • It's a mix between interfaces & classes. BtW, all methods in an interface are implicitly abstract.
    • For example we coulda replaced abstract void action(); w/ void action() {}.
    • But then any1 trying to instantiate that class would fail to realize that method action() isn't complete and needs to be implemented w/ something other than empty.
    • As an experiment, try to instantiate Button w/ just a regular new Button() like:
      btns[0] = new Button(GAP, y, BTN_W, BTN_H, #FF0000) {};
    • It'll fail to compile b/c action() "must" be implemented.
    • Also b/c abstract classes can't be instantiated w/ just new.
    • Now remove the abstract mark from action(): void action() {}
    • It will compile w/o dealing w/ action(). But then action() won't do anything. :P

    P.S.: Notice that in order to directly instantiate an abstract class we need to at least add {};
    after new like new Button() {};.

    However do not add {}; for regular classes. It ends up instantiating them as if they were some derived class for no reason or gain:

    1. new PVector() {}; // WRONG! Derived class object.
    2. new PVector(); // RIGHT! Real PVector object.
  • This is incredibly helpful, thanks so much!

Sign In or Register to comment.