Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

CallBack methods

 
Em Aiy
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Em Aiy
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See this thread.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15369
40
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's a simple example with an interface, and an anonymous inner class in the main() method that implements the interface.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic