Java callback function
In C and C++ programming language, the process of calling a function from another function is referred to as callback. The function’s memory address is represented as the function pointer.
In C and C++ languages, we achieve the callback bypassing the function pointer to another function.
Unlike C and C++ language, Java doesn’t have the concept of the callback function. Java doesn’t use the concept of the pointer, due to which callback functions are not supported. However, we can create a callback function by passing an interface that refers to the location of the function instead of passing the function’s memory address.
The syntax of the callback function in Java using the interface is given below:
How does the Java callback function work?
The callback function in Java works in the following manner:
- Create an interface X having a single method A().
- Create a method method1() with A as a method parameter.
- Call the A() method inside of the method1().
- For calling method1(), we pass the instance of X and override the A().
- Use arrow notation as an alternative to keyword news so that the code is clear.
Let’s take an example and understand a scenario in which we can use callback function in Java,
Example:
We implement the tax calculator that calculates the tax(total tax) for the state. For a state, tax can be more than one but for our example, let’s assume that we have only two taxes, i.e., state tax and central tax. In both the taxes, the central tax will be the same for all states, but state tax may be different for states.
In the above code, the address or the reference of the stateTax() method is passed for calculating the sum of taxes in the calculateTax() method. The state code varies from state to state, so we declare the stateTax() method as an abstract method in the interface.
Below is the implementation of the stateTax() method for Haryana and Utter Pradesh state:
CallbackExample1.java
Output:
CallbackExample2.java
Output:
CallbackExample3.java
Output: