Wednesday, July 20, 2011

Implementing Callback in Java

interface InterestingEvent {
 // This is just a regular method so it can return something or
    // take arguments if you like.
    public void interestingEvent ();

}


class CallMe implements InterestingEvent {
    public CallMe ()
    {
     // en = new EventNotifier (this);
    } 
    // Define the actual handler for the event.
    public void interestingEvent ()
    {
     System.out.println("Wow!  Something really interesting must have occurred!");
    // Do something...
    } 
    //...

}


class EventNotifier {
    private InterestingEvent ie;
    private boolean somethingHappened; 
    public EventNotifier (InterestingEvent event)
    {
    // Save the event object for later use.
    ie = event; 
    // Nothing to report yet.
    somethingHappened = false;
    } 
    //...  
    public void doWork ()
    {
    somethingHappened = true; 
    // Check the predicate, which is set elsewhere.
    if (somethingHappened)
        {
        // Signal the even by invoking the interface's method.
        ie.interestingEvent ();
        }
    //...
    } 
    // ...


}

public class TestCallback {
    
    public static void main(String[] args) {
     CallMe me = new CallMe();
  EventNotifier event = new EventNotifier(me);
  event.doWork();
    }
}


Source: href="http://www.javaworld.com/javaworld/javatips/jw-javatip10.html

Sunday, July 17, 2011

Array of Pointers

A pointer can only point to a single object such as char and int; whereas an array of pointers can point to several objects. For example,


    // void printName(char *p[])
void printName(char **p)  
{
printf("Name1: %s\n", p[0]);
printf("Name2: %s\n", p[1]);
}




int main(int argc, char *argv[])
{
char name1[] = "Name 1";
char name2[] = "Name 2";
char *p[2];


p[0] = name1;
p[1] = name2;


printName(p);


}