Recently I keep coming across the idea of a callback, but I'm having trouble understanding the concept. People have referred to it as a "hook" (um...) and "a value varying function" (aha, no wait, um...). I think I'm begining to get the idea, but a quick question about callbacks in java:
is ActionListener etc. in Swing a callback? If so, what would be a non-swing example of a callback?
technically, ActionListener is a non-Swing example of a callback... they're used in AWT, which is not swing. Swing is based on AWT, but you don't need Swing to use AWT. (though you do want Swing. bare-bones AWT, as i'm finding out recently, isn't much fun.)
definition-wise, a "callback" is a function or method you write for the purpose of handing it (or a reference to it) to some other code (like Swing or AWT) to call when that other code needs to do something inside your code. there's little or no difference between a "callback" and a "hook".
From my understanding of this, a callback function (or method) is one that is called from code that you didn't write yourself. Often this third-party code is involved with the operating system. Swing and AWT are a very common place for this to occur. When writing event handlers, you have probably asked, "Who calls paintComponent()?" The answer is that the Operating System does, albeit a little indirectly. Other methods, like most of the ones defined in event listener interfaces, are similar. These are all callback methods because you register them in some manner and then someone else calls them. You rarely, if ever, call these callback methods directly.
Thanks to all of you for your posts. I think I'm beginning to get it. Would I be right in saying a "callback" is in someway the opposite of an API? You call a function in the API (thread.start()) and then it calls your method (run())? [ March 24, 2005: Message edited by: Gar Morley ]
A callback method is an API, but it's an API you choose to implement rather than one you choose to call.
Imagine a framework that does the tricky bits for running SQL queries. You call it like this:
resultset = framework.runQuery( this );
And the framework requires the object you pass in to implement getTheSQL() to return the actual SQL string. So you call the framework and the framework calls you back. The framework implements the Framework API and you implement the KnowsTheSQL API.
I usually associate "hook" with abstract methods, but I won't argue about using it here. Back on the mainframe callbacks were called User Exits, a name that didn't make near as much sense.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Dec 15, 2004
Cool, thanks people. I think I've got my head around the concept. Now, off to find something else to be puzzled about... =)