Is there a way in java to do something like this:
void fnc(void Reference_to_other_func());
What I’m trying is basically I have number of places where I need to display this same text to the user and the only difference is which method is invoked after this text. So for example instead of writing:
System.out.println("Hello");
f1();
//in some other place
System.out.println("Hello");
f2();
//etc
I would like to define one function:
public void f(void Reference_to_other_func())
{
System.out.println("Hello");
Reference_to_other_func();//HERE I'M INVOKING
}
and then instead of repeating this whole code I could write something like this:
f(f1);
//in some other place
f(f2)
//etc.
Thanks for answers
Java does not have first-class functions, which makes most functional-programming techniques somewhat tedious to implement.
In this case, you can make an interface:
(Edit: or you could use
java.util.concurrent.Callable<V>, which allows you to specify a return type)then declare
fto take an instance of this interface:and pass an instance of this interface to the function:
As you can see, the gains are not going to become apparent unless you’re doing this quite a lot.