Home  >  Article  >  Java  >  Java Callback Function

Java Callback Function

WBOY
WBOYOriginal
2024-08-30 15:33:48419browse

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:

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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.

public interface 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
   public void clickhndlr();
}
//Create a callback handler ClickHandler that implements the clickeventhandlrinterfce interface
class ClickHandler implements clickeventhandlrinterfce {	
	//call method clickhndlr
   public void clickhndlr() {
	   
      System.out.println("Hey. . .  You have Clicked");
   } 
}
//Create  class for event generator
class Button {	
   public void onClick(clickeventhandlrinterfce chndlr)
   {
      chndlr.clickhndlr();
   }
}
public class CallBackFuncExample {	
   public static void main(String[] args) {	   
	  //create an object for btn2
      Button btn1 = new Button();      
      //create an object for ClickHandler
      ClickHandler chndlr = new ClickHandler();      
      //pass the object of  ClickHandler for performing the default operation
      btn1.onClick(chndlr);
	  //create an object for button2
      Button btn2 = new Button();      
      //For implementing own operation, pass the interface     
      btn2.onClick(new clickeventhandlrinterfce() {   	  
         @Override         
         //method clickhndlr that displays output on clicking
         public void clickhndlr() {       	 
            System.out.println("Hey. . .  You have clicked a button");
         }
      });
   } }

Output:

Java Callback Function

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
public class CallBackFuncExample {	
	//main method
    public static void main(String args[]) {
      
    //Function that passes interface name as parameter
      func1(new interfaceA()
      {
    	  //method callA
          public String callA() 
          {
              return "HI, I AM FIRST CALL ";
            }
      } ) ;
      
      // function that passes interface name as parameter
       func1(new interfaceA()
       {
     	  //method callA

        public String callA() {
          return "HI, I AM SECOND CALL";
        }
        } ) ;
        func1(() -> 
        {
                return "HI, I AM THIRD CALL";
        });
    }
    public static void func1(interfaceA intr)
    {
        System.out.println("Method called here: " + intr.callA());
    }  
    public interface interfaceA {
        public String callA();
    }
}

Output:

Java Callback Function

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 {
  void samplefunc(String txt);
}
//create a class that implements the interface
class classA implements textprint {
//create a method samplefunc that takes a text as a parameter 
  public void samplefunc(String txt) {
	  
    System.out.println("The text is : " + txt);
  }
}
//main class
public class CallBackFuncExample {	
  // Reference to the textprint Interface
  textprint txtrcvr;    
  CallBackFuncExample(textprint r) {
    txtrcvr = r ;
  }  
  public void samplefunc2(String s)
  {
    txtrcvr.samplefunc(s);
  }  
  //main method
  public static void main(String[] args) {	  
// Create a object of the classA that implements the interface
    classA objA = new classA();     
    CallBackFuncExample obj2 = new CallBackFuncExample(objA);    
    obj2.samplefunc2("Program runs successfully");
  }
}

Output:

Java Callback Function

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:

import java.util.Scanner; 
//create an interface
interface interfaceA { 	
	double func1(); 
} 
// class A that implements the interface
class A implements interfaceA { 	
	public double func1() 
	{ 
		return 2500.0; 
	} 
} 
//class B that implements the interface
class B implements interfaceA { 
	
	public double func1() 
	{ 
		return 1500.0; 
	} 
} 
class CallBackFuncExample  { 
	//MAIN METHOD
	public static void 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
		Class cl = Class.forName(classnm); 
		interfaceA intr = (interfaceA)cl.newInstance(); 
		func2(intr); 
	} 
	static void func2(interfaceA intrfce) 
	{ 
		double a = 2000.0; 
		double b = intrfce.func1(); 
		double sum = b + a; 
		System.out.println("Total amount is :" + sum); 
	} 
}

Output:

Java Callback Function

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.

The above is the detailed content of Java Callback Function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Recursion in JavaNext article:Recursion in Java