How to implement callback functions in Java?

The callback function is excutable code that is called through a function pointer. You pass a callback function pointer as an argument to other code, or register callback function pointer in somewhere. When something happens, the callback function is invoked.

C/C++ allow function pointers as arguments to other functions but there are no pointers in Java. In Java, only objects and primitive data types can be passed to methods of a class. Java's support of interfaces provides a mechanism by which we can get the equivalent of callbacks. You should declare an interface which declares the function you want to pass.

The collections.sort(List list, Comparator c) is an example of implementing callback function in Java. The c is an instance of a class which implements compare(e1, e2) method in the Comparator interface. It sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator.

Use inner classes to define an anonymous callback class, instantiate an anonymous callback delegate object, and pass it as a parameter all in one line. One of the common usage for inner classes is to implement interfaces in event handling.

class SomePanel extends JPanel {

private JButton myGreetingButton = new JButton("Hello");
private JTextField myGreetingField = new JTextField(20);

private ActionListener doGreeting = new ActionListener {
public void actionPerformed(ActionEvent e) {

public SomePanel() {
// . . . Layout the panel.


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |