Back

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

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

1 Answer

0 votes
by (19.7k 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.

Related questions

Browse Categories

...