匿名內部類
將局部內部類的使用再深入一步。假設只創建這個類的一個對象,就不必命名了。這種類成爲匿名內部列(anonymous inner class)。
public void start(int interval, boolean beep) {
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("At the thone, the time is " + new Date());
if (beep) Toolkit.getDefaultToolkit.beep();
}
}
Timer t = new Timer(interval, listener);
t.start();
}
這種語法確實有些難以理解。它的含義是:創建一個實現ActionListener接口的類的新對象,需要實現的方法actionPerformed定義在括號{}內。
通常的語法格式爲:
new SuperType(construction parameters) {
inner class methods and data
}
其中,SuperType可以是ActionListener這樣的接口,於是內部類就要實現這個接口。SuperType也可以是一個類,於是內部類就要擴展它。
由於構造器的名字必須與類名相同,而匿名類沒有類名,所以,匿名類不能有構造器。取而代之的是,將構造器參數傳遞給超類(superclass)構造器。尤其是在內部類實現接口的時候,不能有任何構造參數。不僅如此,還要像下面這樣提供一組括號:
new InterfaceType() {
methods and data
}
請仔細研究一下,看看構造一個類的新對象與構造一個擴展了那個類的匿名內部類的對象之間有什麼差別。
Person queen = new Person("Mary");
Person count = new Person("Dracula"){...};
如果構造參數的閉小括號後面跟一個開大括號,正在定義的就是匿名內部類。
多年來,Java程序員習慣的做法是用匿名內部類實現事件監聽器和其他回調。如今最好還是使用lambda表達式,使用lambda表達式會簡潔很多,如:
public void start(int interval, boolean beep) {
Timer t = new Timer(interval, event -> {
System.out.println("At the tone, the time is " + new Date());
if (beep) Toolkit.getDefaultToolkit().beep();
});
}
實例
package cn.freedompc.anonymousinnerclass;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.Timer;
public class AnonymousInnerClassTest {
public static void main(String[] args) {
TalkingClock clock = new TalkingClock();
clock.start(1000, true);
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}
class TalkingClock {
public void start(int interval, boolean beep) {
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("At the tone, the time is " + new Date());
if (beep) Toolkit.getDefaultToolkit().beep();
}
};
Timer t = new Timer(interval, listener);
t.start();
}
}
結果:
捐贈
若你感覺讀到這篇文章對你有啓發,能引起你的思考。請不要吝嗇你的錢包,你的任何打賞或者捐贈都是對我莫大的鼓勵。