首頁  >  文章  >  Java  >  Java回呼函數

Java回呼函數

WBOY
WBOY原創
2024-08-30 15:33:48379瀏覽

回呼是一種在事件驅動程式設計中發生特定事件時呼叫傳遞給函數的參考的機制。對於 C、C++ 等程式語言,回呼是透過將 function1 指標傳遞給 function2 來實現的。由於Java不支援指針,因此無法這樣實現回調。為此,在引用函數位置的地方建立並傳遞介面。在本文中,將討論有關回調函數的更多細節。

文法:

廣告 該類別中的熱門課程 JAVA 掌握 - 專業化 | 78 課程系列 | 15 次模擬測驗

開始您的免費軟體開發課程

網頁開發、程式語言、軟體測試及其他

下面是回呼函數的語法,其中存在一個帶有回呼函數的介面。這個方法稍後會在類別中使用。

public interface interfaceA {
public String callA() ;
}

Java 回呼函數如何運作?

讓我們看看回呼函數是如何以簡單的方式運作的。

  • 僅使用一個方法 callA() 建立一個介面。
  • 建立一個方法 func1,並將 A 作為方法參數。
  • 在 func1 中呼叫 callA()。
  • 傳遞 A 的新實例並重寫方法 callA() 來呼叫 func1。
  • 使用箭頭表示法作為關鍵字 news 的替代,使程式碼看起來更乾淨。

Java回呼函數實作範例

以下是一些java回呼函數的範例程式。

範例#1

點擊按鈕時列印文字的 Java 程式。

代碼:

//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");
         }
      });
   } }

輸出:

Java回呼函數

說明:先為button1、ClickHandler、button2建立一個物件。然後傳遞Click Handler物件來執行預設操作。之後,為了實現其自己的操作,請使用 clickhndlr 方法傳遞接口,該方法在單擊時顯示輸出。所有這些完成後,為回呼方法建立一個介面clickeventhandlinterfce。然後,建立一個實作 clickeventhandlrinterfce 介面的回呼處理程序 ClickHandler,最後為事件產生器建立一個類別。執行程式碼時,將列印兩行,如上面的範例輸出所示。

範例#2

實作回呼函數的簡單java程式。

代碼:

//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();
    }
}

輸出:

Java回呼函數

說明:在此程式中,僅使用一個方法 callA() 建立一個介面。然後,使用interfaceA 作為方法參數建立另一個方法func1。之後,在func1內部呼叫interfaceA.callA()。完成這些步驟後,傳遞一個新的 interfaceA 實例並重寫方法 callA() 來呼叫 func1。這裡使用箭頭表示法來取代關鍵字new,以使程式碼看起來更乾淨。執行程式碼可以看到呼叫了三個方法,並傳回了結果,如上圖

範例#3

實作回呼函數並列印字串的Java程式。

代碼:

//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");
  }
}

輸出:

Java回呼函數

說明:在這個程式中,建立一個介面並建立一個實作該介面的類別。在該類別中,建立一個方法samplefunc,它將文字作為參數。使用建立的類別對象,呼叫該方法,並在執行程式碼時列印字串。

範例#4

根據類別將兩個數字相加的 Java 程式。

代碼:

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

輸出:

Java回呼函數

說明:在這個程式中,建立了接口,並呼叫了類別方法。此處,根據使用者輸入使用回呼函數求兩個金額的總和。

以上是Java回呼函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:Java 中的遞迴下一篇:Java 中的遞迴