Introduction to Java Callback Function
A callback is a mechanism when a reference that is passed to a function gets called when a particular event occurs in Event-driven programming. In cases of programming languages such as C, C++, the callback is attained by passing the function1 pointer to function2. As Java does not support pointers, the callback cannot be implemented like this. For that, interfaces are created and passed where the location of a function is referred. In this article, more details on the callback function will be discussed.
Syntax:
Below is the syntax of the callback function where an interface with a callback function is present. This method will be used later inside the class.
publicinterface interfaceA {
public String callA() ;
}
How Does Java Callback Function Work?
Let us see how the callback function works in a simple manner.
- Create an interface With just one method callA().
- Create a method func1with A as a method parameter.
- Call callA()inside func1.
- Pass a new instance of A and override the method callA() for calling the func1.
- Use arrow notation as an alternative to the keyword news so that code looks cleaner.
Examples to Implement Java Callback Function
The following are some sample programs on java callback functions.
Example #1
Java program that prints text when the button is clicked.
Code:
//Create an interface clickeventhandlrinterfce for the callback method
interface clickeventhandlrinterfce {
//call method clickhndlr
publicvoidclickhndlr();
}
//Create a callback handler ClickHandler that implements the clickeventhandlrinterfce interface
class ClickHandler implements clickeventhandlrinterfce {
//call method clickhndlr
publicvoidclickhndlr() {
System.out.println("Hey. . . You have Clicked");
}
}
//Create class for event generator
class Button {
publicvoidonClick(clickeventhandlrinterfce chndlr)
{
chndlr.clickhndlr();
}
}
publicclass CallBackFuncExample {
publicstaticvoid main(String[] args) {
//create an object for btn2
Button btn1 = newButton();
//create an object for ClickHandler
ClickHandler chndlr = newClickHandler();
//pass the object of ClickHandler for performing the default operation
btn1.onClick(chndlr);
//create an object for button2
Button btn2 = newButton();
//For implementing own operation, pass the interface
btn2.onClick(newclickeventhandlrinterfce() {
@Override
//method clickhndlr that displays output on clicking
publicvoidclickhndlr() {
System.out.println("Hey. . . You have clicked a button");
}
});
} }

4.8 (13,761 ratings)
View Course
Output:
Explanations: Firstly, create an object for button1, ClickHandler, and button2. Then pass the object of Click Handler for performing the default operation. After that, for implementing its own operation, pass the interface with a method clickhndlr that displays output on clicking. Once all these are done, create an interface clickeventhandlrinterfce for the callback method. Then, create a callback handler ClickHandler that implements the clickeventhandlrinterfce interface and, at last, creates a class for the event generator. On executing the code, two lines will be printed, as shown above in the sample output.
Example #2
Simple java program that implements callback function.
Code:
//class starts here
publicclass CallBackFuncExample {
//main method
publicstaticvoidmain(String args[]) {
//Function that passes interface name as parameter
func1(newinterfaceA()
{
//method callA
public String callA()
{
return"HI, I AM FIRST CALL ";
}
} ) ;
// function that passes interface name as parameter
func1(newinterfaceA()
{
//method callA
publicStringcallA() {
return"HI, I AM SECOND CALL";
}
} ) ;
func1(() ->
{
return"HI, I AM THIRD CALL";
});
}
publicstaticvoid func1(interfaceA intr)
{
System.out.println("Method called here: " + intr.callA());
}
publicinterface interfaceA {
public String callA();
}
}
Output:
Explanations: In this program, an interface is created with just one method callA(). Then, another method, func1, is created with interfaceA as a method parameter. After that, call interfaceA.callA() inside func1. Once these steps are completed, pass a new instance of interfaceA and override the method callA() for calling the func1. Here an arrow notation is used as an alternative to the keywordnew so that code looks cleaner. On executing the code, it can be seen that three methods are called, and the results are returned, as shown in the figure above.
Example #3
Java program that implements callback function and prints a string.
Code:
//create an interface
interface textprint {
voidsamplefunc(String txt);
}
//create a class that implements the interface
class classA implements textprint {
//create a method samplefunc that takes a text as a parameter
publicvoidsamplefunc(String txt) {
System.out.println("The text is : " + txt);
}
}
//main class
publicclassCallBackFuncExample {
// Reference to the textprint Interface
textprint txtrcvr;
CallBackFuncExample(textprint r) {
txtrcvr = r ;
}
publicvoid samplefunc2(String s)
{
txtrcvr.samplefunc(s);
}
//main method
publicstaticvoid main(String[] args) {
// Create a object of the classA that implements the interface
classA objA = newclassA();
CallBackFuncExample obj2 = new CallBackFuncExample(objA);
obj2.samplefunc2("Program runs successfully");
}
}
Output:
Explanations: In this program, create an interface and create a class that implements the interface. Inside that class, create a method samplefunc that takes a text as a parameter. Using the created class object, the method is called, and the string gets printed on executing the code.
Example #4
Java program that adds two numbers based on the class.
Code:
importjava.util.Scanner;
//create an interface
interface interfaceA {
double func1();
}
// class A that implements the interface
class A implements interfaceA {
publicdouble func1()
{
return 2500.0;
}
}
//class B that implements the interface
class B implements interfaceA {
publicdouble func1()
{
return 1500.0;
}
}
classCallBackFuncExample {
//MAIN METHOD
publicstaticvoid main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException
{
//scanner object
Scanner sc = new Scanner(System.in);
System.out.println("Enter the class name");
String classnm = sc.next();
// object is then stored in cl
Classcl = Class.forName(classnm);
interfaceA intr = (interfaceA)cl.newInstance();
func2(intr);
}
staticvoid func2(interfaceA intrfce)
{
doublea = 2000.0;
doubleb = intrfce.func1();
doublesum = b + a;
System.out.println("Total amount is :" + sum);
}
}
Output:
Explanations: In this program, the interface is created, and the class methods are called. Here, a sum of two amounts is found using the callback function based on the user input.
Recommended Articles
This is a guide to Java Callback Function. Here we discuss Java Callback Function’s concept through definition and their methods along with programming examples and their outputs. You can also go through our other suggested articles to learn more –