Interface to implement call back functions

Example to implement callback method using interface.

Define the interface, NewInterface.java.
?
1
2
3
4
5
package javaapplication1;
 
public interface NewInterface {
    void callback();
}


Create a new class, NewClass.java. It will call the callback method in main class.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package javaapplication1;
 
/**
 *
 */
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.

No comments:

Post a Comment