I have been trying to wrap my head around callbacks and have been struggling to grasp the concept. The following code is an example that I found here
starting from first to last I understand the flow to be such:
CallMe
is instantiated, thus calling the constructor of said class- The variable
en
is set, subsequently instantiating theEventNotifier
class and calling it's constructor which is passed a reference to the objectCallMe
- The variable
ie
is set to the objectCallMe
which was passed into the constructor - The variable
somethinghappened
is set to false (I would assume some conditional statement would be used to determine whether or not to set the value otherwise) - Ummm... done?
I do not understand this code. How does doWork
get called? How does this signify an event? Why would one not simply call interestingevent
from the constructor of callme
.... For that matter why not just call dowork
in place of whatever would change the value of somethinghappened
?
Try as I might I cannot seem to grasp the idea. I understand that callbacks are used primarily to signify an event has occurred such as a mouse or button click but how does it make the connection between the event occurring and the methods being called? Should there not be a loop that checks for changes, and thus triggers the event?
Can someone please provide a (not over-simplified) explanation of callbacks in java and help clarify how something like this could be useful?
public interface InterestingEvent
{
public void interestingEvent ();
}
public class EventNotifier
{
private InterestingEvent ie;
private boolean somethingHappened;
public EventNotifier (InterestingEvent event)
{
ie = event;
somethingHappened = false;
}
public void doWork ()
{
if (somethingHappened)
{
ie.interestingEvent ();
}
}
}
public class CallMe implements InterestingEvent
{
private EventNotifier en;
public CallMe ()
{
en = new EventNotifier (this);
}
public void interestingEvent ()
{
// Wow! Something really interesting must have occurred!
// Do something...
}
}
EDIT: please see the comments in the approved answer... ---this--- link was very helpful for me =)