Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Make parameter to a method another method

Tags:

java

methods

I want to make a method that does a specific task, but then calls another method with the results of that task. Well easy enough, but the trick is that I want the method (the second one thats getting called by the first one) to be a parameter of the first method.

I probably explained that terribly, so here is what I think it might look like

public static void main(String[] args) {
    double[][] data = {
        {2,6},
        {-32,5}
    }

    loop(data,{System.out.println(row * col)});
}

public static void loop(double[][] data,somemethod(row,col)) {
    for (int row = 0;row < data.length;row++)
        for (int col = 0;col < data[0].length;col++)
            somemethod(row,col);
}

So the loop method does a task, and then runs the code that was passed as a parameter. Can this be done in java? I feel like I have seen it somewhere.

like image 628
Hurricane Development Avatar asked Feb 13 '26 00:02

Hurricane Development


1 Answers

The pre-Java-8 way to do this was by creating an interface with the method you want called:

interface MyCallback {
    void someMethod(int row, int col);
}

You create an object with the implementation you want:

class MyCallbackImpl implements MyCallback {

    public void somemethod(int row, int col) {
        System.out.println(row * col);
    }
}

and have the method take a parameter implementing that interface:

public static void loop(double[][] data, MyCallback mycallback) {
    for (int row = 0;row < data.length;row++)
        for (int col = 0;col < data[0].length;col++)
            mycallback.somemethod(row,col);
}

If you'd rather not create a separate named class for this you have the alternative of creating an object using an anonymous inner class, calling your loop method like:

loop(data, new MyCallback() {
    public void somemethod(int row, int col) {
        System.out.println(row * col);
    }});
like image 92
Nathan Hughes Avatar answered Feb 15 '26 13:02

Nathan Hughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!