0

I am trying to understand callbacks in Java, but it's confusing me a lot. I know callbacks are passed as an object by implementing interface. But I'm not able to understand how the functions of those passed objects in arguments are invoked. I took this example

interface ClickEventHandler {
    public void handleClick();
}
//Step 2: Create a callback handler
//implementing the above interface
class ClickHandler implements ClickEventHandler {
    public void handleClick() {
      System.out.println("Clicked");
    }
}

//Step 3: Create event generator class
class Button {
    public void onClick(ClickEventHandler clickHandler) {
      clickHandler.handleClick();
    }
}

public class Tester {
    public static void main(String[] args) {
        Button button = new Button();
        ClickHandler clickHandler = new ClickHandler();
        //pass the clickHandler to do the default operation
        button.onClick(clickHandler);

        Button button1 = new Button();
        //pass the interface to implement own operation
        button1.onClick(new ClickEventHandler() {
            @Override
            public void handleClick() {
                System.out.println("Button Clicked");
            }
        });
    }
}

Output is 
```none
Clicked Button
Clicked.

I mean to invoke the function of passed objects we need to register it and call the functions. How does it work in case of listeners? It would be helpful if someone guide me in understanding this.

7
  • 1
    You are calling handleClick when you are assigning the click handler! You should call handleClick when the click is performed! Commented Apr 18, 2021 at 7:07
  • 1
    The key is the use of the interface. This describes the expected functionality which might be executed by the object been observed. So, passing an instance of an object which implements ClickEventHandler means that object can call the handleClick, because it guarantees the implementation (hay polymorphism!) Commented Apr 18, 2021 at 7:07
  • 1
    you can check out java2s.com/Code/Java/Event/CreatingaCustomEvent.htm Commented Apr 18, 2021 at 7:08
  • @JaysmitoMukherjee thanks for sharing the example.Helped me alot.
    – Ash3060
    Commented Apr 18, 2021 at 7:56
  • @MadProgrammer correct if me if i am wrong.In general,If we have to use some callback function in class,then there should be some function in the class which will call the callback function. So for that we need to create an interface with the callback function name and implement it and then we should pass it to object method of the class to register it and then we call the object function which calls the callback code.
    – Ash3060
    Commented Apr 18, 2021 at 7:56

3 Answers 3

1

Well, you'd normally maintain a reference to ClickEventHandler (or even a list if you want to support multiple) and call the method when the button is clicked.

Example:

class Button {
  private ClickEventHandler clickHandler;

  public void onClick(ClickEventHandler clickHandler) {
    this.clickHandler = clickHandler;
  }

  public void click() {
     if( clickHandler != null ) {
       clickHandler.handleClick();
     }
  }

Now when you invoke onClick() the listener is only registered and it will only be executed when the button is clicked (i.e. you call the click() method).

0

Its easy you just need to create interface

interface HandleClick {
    void onItemClick(Boolean success);
}

There's some function to do some work and you need something to return

public static void someFunctions(String params, HandleClick handleClick) {
    //some work to do here.
    handleClick.onItemClick(true);
}

You can call it anywhere

class Main extends AppCompatActivity  {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);

        Callbacks.someFunctions("param", new HandleClick() {
            @Override
            public void onItemClick(Boolean success) {

            }
        });
    }

}
1
  • Throwing in Android-specific code might confuse the OP more. Nothing in the question indicates they're using Android, and callbacks are applicable to more than just Android.
    – Slaw
    Commented Apr 18, 2021 at 7:42
0

I wrote a simple code to understand how we can do the same callback in 2 different ways.

interface InterestingEvent
{

public void interestingEvent ();
}


public class Test
{
    private InterestingEvent ie;
    public void EventNotifier (InterestingEvent event)
    {
    ie = event;    
    ie.interestingEvent();
    } 
   
    public static void main(String[] args) {
        
        Test test= new Test();
        test.EventNotifier(new InterestingEvent() {
            
            @Override
            public void interestingEvent() {
                System.out.println("I am callback code");
                
            }
        });
        
    }
}

public class Test implements InterestingEvent{

@Override
public void interestingEvent() {
    System.out.println("Hello i am callback code");
    
}

public void EventNotifier ()
{
    this.interestingEvent();
} 

public static void main(String[] args) {
    
    Test test =new Test();
    test.EventNotifier();
}

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.