aspose file tools*
The moose likes Java in General and the fly likes CallBack methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "CallBack methods" Watch "CallBack methods" New topic
Author

CallBack methods

Em Aiy
Ranch Hand

Joined: May 11, 2006
Posts: 226
hi

there have been options that we don in c/c++ that we can make callback function ... i.e on a particular event the function calls automatically (provided the name of the pointer to the function).

how can we do this in java.


The difference between <b>failure</b> and <b>success</b> is often being <b>right</b> and being <b>exactly right</b>.
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
In C, call-backs are done by passing function pointers, as you suggest. In C++, the C approach works, but is not recommended, as it is not object-oriented.

In C++ and Java, it is better to define a call-back interface and then to pass an object implementing that call-back interface. That's the more object-oriented way.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Em Aiy
Ranch Hand

Joined: May 11, 2006
Posts: 226
thanks peter, but can you explain it in a bit detail.

well, one more thing confusing is taht, in c we tell exactly which function is to call by telling its pointer, but the way you are telling is telling the object. now we have to explicitly call the specified function from that class, isn't it so?

i have seen a call back method type api in winPCap api, which is used to analyze the network trafic. how may they have implemented things?
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
See this thread.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14348
    
  22

Here's a simple example with an interface, and an anonymous inner class in the main() method that implements the interface.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
 
wood burning stoves
 
subject: CallBack methods