Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

I have a method that's about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code. This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers. What's my best alternative?

1 Answer

0 votes
by (46k points)

Anonymous inner class

Say you require to have a function transferred in with a Stringparam that returns an int.

First, you have to define an interface with the function as its only member if you can't reuse an existing one.

interface StringFunction {

    int func(String param);

}

A way that takes the pointer would just allow StringFunction instance like so:

public void takingMethod(StringFunction sf) {

   int i = sf.func("my string");

   // do whatever ...

}

And would be named like so:

ref.takingMethod(new StringFunction() {

    public int func(String param) {

        // body

    }

});

 In Java 8, you could call it with a lambda expression:

ref.takingMethod(param -> bodyExpression);

Related questions

0 votes
1 answer
asked Oct 31, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Sep 11, 2019 in Java by Krishna (2.6k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...