0 votes
1 view
in Java by (9.2k points)

Can anyone help understand the callback method in Java with an example code? 

1 Answer

0 votes
by (19k points)

A callback method passes an argument to other code which executes it. Java doesn’t have function pointers so it implements command objects like below:

public class Test {

    public static void main(String[] args) throws  Exception {

        new Test().doWork(new Callback() { // implementing class            

            @Override

            public void call() {

                System.out.println("callback called");

            }

        });

    }

    public void doWork(Callback callback) {

        System.out.println("doing work");

        callback.call();

    }

    public interface Callback {

        void call();

    }

}

A callback method holds a reference which has all dependencies to your code. It helps you to gain indirection between your code and the code that’s executing the callback. 

Interested in Java? Check out this Java tutorial by Intellipaat.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...