Back

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

Is there a way to pass a call back function in a Java method?

The behavior I'm trying to mimic is a .Net Delegate being passed to a function.

I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.

1 Answer

0 votes
by (46k points)

If you mean somthing like .NET anonymous delegate, I think Java's anonymous class can be used as well.

public class Main {

    public interface Visitor{

        int doJob(int a, int b);

    }

    public static void main(String[] args) {

        Visitor adder = new Visitor(){

            public int doJob(int a, int b) {

                return a + b;

            }

        };

        Visitor multiplier = new Visitor(){

            public int doJob(int a, int b) {

                return a*b;

            }

        };

        System.out.println(adder.doJob(10, 20));

        System.out.println(multiplier.doJob(10, 20));

    }

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Mar 3, 2021 in Java by Jake (7k points)

Browse Categories

...