Monday, February 4, 2013

Implement callback method, using interface.

Example to implement callback method using interface.

Define the interface, NewInterface.java.
package javaapplication1;

public interface NewInterface {
    void callback();
}



Create a new class, NewClass.java. It will call the callback method in main class.
package javaapplication1;

public class NewClass {
    
    private NewInterface mainClass;
    
    public NewClass(NewInterface mClass){
        mainClass = mClass;
    }
    
    public void calledFromMain(){
        //Do somthing...
        
        //call back main
        mainClass.callback();
    }
}


The main class, JavaApplication1.java, to implement the interface NewInterface - callback() method. It will create and call NewClass object. Then, the NewClass object will callback it's callback() method in turn.
package javaapplication1;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaApplication1 implements NewInterface{
    
    NewClass newClass;

    public static void main(String[] args) {
        
        System.out.println("test...");
        
        JavaApplication1 myApplication = new JavaApplication1();
        myApplication.doSomething();

    }
    
    private void doSomething(){
        newClass = new NewClass(this);
        newClass.calledFromMain();
    }

    @Override
    public void callback() {
        System.out.println("callback");
    }

}


Implement callback method, using interface.
Implement callback method, using interface.

3 comments:

  1. Thanks... Got it
    Well Explained,

    ReplyDelete
  2. What are the advantages of Callback interface? Can you please explain it.

    ReplyDelete
  3. @jay2me : it is useful when you develop our own library

    ReplyDelete