Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you set a method to a variable? [closed]

Tags:

java

Is it possible to do something like this in Java

private ? /* (I dont know what Class to use) */ shortcutToMethod = redundantMethod(game.getGraphics());

So instead of calling redundantMethod(game.getGraphics().doThisMethod());

I could just do shortCutToMethod.doThisMethod();

Is this possible?

like image 430
Erick Moore Avatar asked Jan 22 '19 07:01

Erick Moore


People also ask

Can we assign a method to variable?

Java 8 has introduced the idea of a Functional Interface, which allows you to essentially assign methods to variables. It includes a number of commonly-used interfaces as well.

Can you store a method into a variable?

Yeah you can do that. You have the Method class.

Can we assign method to variable in Java?

The only requirement is that is must have a single abstract method.

What happens if a variable or a method is private?

The scope of a private member (variable or method) is restricted only within the class in which it is defined. It cannot be accessed outside the class in which it is defined.


2 Answers

In Java, there are various ways. If you take a look at java.util.function package, you can see

  • Function: Takes one argument, produces one result
  • Consumer: Takes one argument, produces nothing.
  • BiConsumer: Takes two arguments, produces nothing.
  • Supplier: Takes no argument, produces one result.
  • Predicate: Boolean value function of one argument

You can used them as inputs for your method and execute it within.

like image 195
mkjh Avatar answered Oct 04 '22 05:10

mkjh


Java 8 has introduced the idea of a Functional Interface, which allows you to essentially assign methods to variables. It includes a number of commonly-used interfaces as well.

Common examples:

  • Consumer<T> - a method that takes in T and returns void
  • Function<T, R> - a method that takes in T and returns R
  • Supplier<R> - a method that takes no arguments and returns R
  • Runnable - a method that takes no arguments and returns void
  • Predicate<T> - a method that takes in T and returns boolean

In your case, you appear to be after a Runnable:

Runnable shortcutToMethod = () -> redundantMethod(game.getGraphics());
shortcutToMethod.run();
like image 42
Joe C Avatar answered Oct 04 '22 03:10

Joe C