Java 使用接口的回调
C/C++中的回调: 从另一个函数调用一个函数的机制被称为 “回调”。在C和C++等语言中,一个函数的内存地址被表示为 “函数指针”。因此,回调是通过将函数1()的指针传递给函数2()来实现的。
Java中的回调 : 但回调函数的概念在Java中并不存在,因为Java没有指针的概念。然而,在有些情况下,人们可以说是回调对象或回调接口。与其传递函数的内存地址,不如 传递指向函数位置的接口。
例子
让我们举个例子来了解回调的使用范围。假设一个程序员想设计一个税收计算器,计算一个州的总税收。假设只有两种税,中央税和州税。中央税是通用的,而州税则因州而异。总税是这两种税的总和。在这里,每个州都有单独的方法,如stateTax(),并从另一个方法calculateTax()中调用该方法,如:
static void calculateTax(address of stateTax() function)
{
ct = 1000.0
st = calculate state tax depending on the address
total tax = ct+st;
}
在前面的代码中,stateTax()的地址被传递给calculateTax()。calculateTax()方法将使用该地址调用某个州的stateTax()方法,并计算出该州的税收’st’。
由于stateTax()方法的代码从一个州到另一个州都会改变,所以最好将其作为一个抽象方法在接口中声明,如:
interface STax
{
double stateTax();
}
以下是旁遮普州的stateTax()的实现:
class Punjab implements STax{
public double stateTax(){
return 3000.0;
}
}
以下是惠普州的stateTax()的实现:
class HP implements STax
{
public double stateTax()
{
return 1000.0;
}
}
现在,calculateTax()方法可以设计为:
static void calculateTax(STax t)
{
// calculate central tax
double ct = 2000.0;
// calculate state tax
double st = t.stateTax();
double totaltax = st + ct;
// display total tax
System.out.println(“Total tax =”+totaltax);
}
在这里,观察一下calculateTax()方法中的参数’STax t’。t’是’STax’接口的一个引用,作为一个参数传递给该方法。使用这个引用,stateTax()方法被调用,如:
double st = t.stateTax();
在这里,如果’t’指的是Punjab类的stateTax()方法,那么该方法就会被调用并计算其税金。同样,对于HP类,也是如此。这样,通过向calculateTax()方法传递接口引用,就有可能调用任何州的stateTax()方法。这被称为 回调机制。
通过传递指向某个方法的接口引用,就有可能从另一个方法中调用和使用该方法。
// Java program to demonstrate callback mechanism
// using interface is Java
// Create interface
import java.util.Scanner;
interface STax {
double stateTax();
}
// Implementation class of Punjab state tax
class Punjab implements STax {
public double stateTax()
{
return 3000.0;
}
}
// Implementation class of Himachal Pradesh state tax
class HP implements STax {
public double stateTax()
{
return 1000.0;
}
}
class TAX {
public static void main(String[] args)
throws ClassNotFoundException, IllegalAccessException, InstantiationException
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the state name");
String state = sc.next(); // name of the state
// The state name is then stored in an object c
Class c = Class.forName(state);
// Create the new object of the class whose name is in c
// Stax interface reference is now referencing that new object
STax ref = (STax)c.newInstance();
/*Call the method to calculate total tax
and pass interface reference - this is callback .
Here, ref may refer to stateTax() of Punjab or HP classes
depending on the class for which the object is created
in the previous step
*/
calculateTax(ref);
}
static void calculateTax(STax t)
{
// calculate central tax
double ct = 2000.0;
// calculate state tax
double st = t.stateTax();
double totaltax = st + ct;
// display total tax
System.out.println("Total tax =" + totaltax);
}
}
输出:
Enter the state name
Punjab
Total tax = 5000.0