java 回撥函式示例

hgs19921112發表於2018-08-20
public class Callback {
    static A a= null;
public static void main(String[] args) {
int x = 100;
a = new A(x,new B() {
@Override
void otherAuth() {
//2.呼叫自己的函式
int num = this.Changethenum(a.a);
//3. 回撥A的callBack
a.callBack(num);
}
});
//1.A 調自己的callB
a.callB();
}
}
abstract class B{
public B( ) {
}
abstract void otherAuth();
public int Changethenum(int num) {
return (int) Math.pow(num, 3);
}
}
class A  {
int a ;
B b = null;
A(int a , B b ){
this.a = a ;
this.b = b;
}
void callB(){
b.otherAuth();
}
void callBack(int i ) {
System.out.println("The number changed : "+i);
}
}


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/31506529/viewspace-2212326/,如需轉載,請註明出處,否則將追究法律責任。

相關文章