Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Parameter of a method - a method

 
Urs Waefler
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Is it possible to have as a parameter of a method a method? Maybe there must be a return typ.

int A (int A()) {}

OR

int B (int C ()) {}

Does anybody know an example?

Regards
Urs
 
Srikanth Ramu
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess its not possible to have a method as a parameter. The Parameter of a method should be a datatype.
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could not define a method as a formal parameter, but you can send in a method as an actual parameter. This method should return the parametertype which is expected as formal parametertype in the method.

Here is a working code example

 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remko, what your code demonstrates is not passing a method as a parameter to another method. All it does is pass the return value of a method to another method. It's exactly the same as this:

Urs, no, Java does not have "method references" built-in into the language (like function pointers in C or C++). It is possible in Java with reflection. But usually you do not need something like that, it is not good object-oriented design. A better way to do this is to just pass an object reference to the method; the called method can call methods on that object. Through polymorphism you can have different behaviours at runtime.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic