Passing a method-reference to an objects constructor
14:59 27 Aug 2016

I feel that I'm missing something when it comes to statically typed languages. When I pretty much only used perl way back, there were many ways I could tell an object which function to call.

Now that I'm in Java, I fail to see how I can do something similar in an easy fashion.

I have a generic Button class. This is subclassed by all of the actual buttons that will be used: each with a different method to call when clicked.

Is there really no way of passing a reference to a method to call when clicked, so that I can use one class for all of the buttons?

At present, I create buttons like this:

// Specifically using the subclass that sets "firemode" to "close"
FiremodeClose fc = new FiremodeClose(Settings.ui_panel_start, Settings.ui_panel_row_firemode, game);
painter.addSelectionButton(fc);
clickTracker.addSelectionButton(fc);

This of course causes a myriad of subclasses, each one differing only in placement, label/graphics, and method call. It makes more sense to do something similar to this:

// Generic button, the method that sets "firemode" is somehow passed as argument to the constructor.
Button fc = new Button(&referenceToFunctionToCallWhenClicked, otherArgumentsEtc);
painter.addSelectionButton(fc);
clickTracker.addSelectionButton(fc);

Like I said, I feel I must be missing something, because it makes sense that there should be a way of achieving this, thus letting me getting away with just one Button class without any subclasses.

java parameter-passing simplify