专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java回调接口的例子

Java回调接口的例子

更新时间:2022-11-21 10:17:42 来源:赢咖4 浏览922次

Java中的回调:但是Java中不存在回调函数的概念,因为Java没有指针概念。但是,在某些情况下,我们可以谈论回调对象或回调接口。不是传递函数的内存地址,而是传递引用函数位置的接口。

例子

让我们举个例子来理解在哪里可以使用回调。假设一个程序员想要设计一个税收计算器来计算一个州的总税收。假设只有两种税,中央税和州税。中央税很普遍,而州税因州而异。总税额为两者之和。这里为每个州实现了像 stateTax() 这样的单独方法,并从另一个方法 calculateTax() 调用此方法,如下所示:

static void calculateTax(stateTax() 函数的地址)
{
    ct = 1000.0
    st = 根据地址计算州税
    总税额 = ct+st;
}

在前面的代码中,stateTax() 的地址被传递给 calculateTax()。calculateTax() 方法将使用该地址调用特定州的 stateTax() 方法,并计算州税“st”。

由于 stateTax() 方法的代码从一种状态变为另一种状态,因此最好将其声明为接口中的抽象方法,如:

接口标准税
{
     双州税();
}

以下是旁遮普邦的 stateTax() 的实现:

类旁遮普实现 STax{
    公共双州税(){
    返回 3000.0;
     }
}

以下是 HP 状态的 stateTax() 的实现:

类 HP 实现 STax
{
    公共双重 stateTax()
    {
        返回 1000.0;
    }
}

现在,calculateTax() 方法可以设计为:

static void calculateTax(STax t)
{
    // 计算中央税
    双 ct = 2000.0;
    // 计算州税
    双 st = t.stateTax();
    双总税 = st + ct;
    // 显示总税额
    System.out.println(“总税额=”+totaltax);
}

在这里,观察 calculateTax() 方法中的参数“STax t”。't' 是作为参数传递给方法的 'STax' 接口的引用。使用此引用,调用 stateTax() 方法,如下所示:

双 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);
	}
}

输出:

输入州名
旁遮普语
总税额 = 5000.0

 

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>