Java callback functionIn 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:
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: Next TopicJava 8 vs Java 11 |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India