簡體   English   中英

是否將接口的對象初始化為方法的參數?

[英]Intitialising an object of an interface as an argument of a method?

據我所知,您不能創建接口的對象,而可以實現接口的類的對象,但是,在查看有關事件處理程序的教程時,我發現了以下內容:

  b.addActionListener(new ActionListener(){  
public void actionPerformed(ActionEvent e){  
        tf.setText("Welcome to Javatpoint.");  
}  
});  

首先,我不知道您可以在方法的參數內構造對象。 其次,我知道ActionListener是一個接口,那么new ActionListener到底在做什么? 閱讀后,我得到一個模糊的想法,即它實際上是在創建一個實現Action Listener的新類,但是該類叫什么呢? 我可以制作此類的其他對象嗎? 最后,以上代碼與以下代碼有何不同:

//where MyActionListener is a class that implements ActionListener

MyActionListener objectOfActionListener = new MyActionListener();
b.addActionListener(objectOfActionListener);

//and the method for actionPerformed is in the MyActionListener class

這是一個實現ActionListener接口的匿名類

您當然可以創建自己的顯式類並將其實例化,但是除非您需要在多個地方重復使用相同的邏輯,否則沒有太大的好處。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM