问题描述
我想问一个有关实例化ActionListener对象的问题。
作为Java入门课程的一部分,我编写了以下代码:
// anonymous classes
import java.awt.event.*;
import javax.swing.*;
public class TickTockAnonymous {
private String tickMessage = "Tick...";
private String tockMessage = "Tock...";
public static void main (String [] args) {
TickTockAnonymous t = new TickTockAnonymous();
t.go();
}
private void go () {
// create a timer that calls the Ticker Class at one second intervals
Timer t = new Timer (1000,new ActionListener() {
private boolean tick = true;
public void actionPerformed (ActionEvent event)
{
if (tick)
{
System.out.println(tickMessage);
}
else
{
System.out.println(tockMessage);
}
tick = !tick;
}
});
t.start();
// display a message Box to prevent the program from terminating immediately
JOptionPane.showMessageDialog(null,"Click OK to exit program");
System.exit(0);
}
}
此代码有效。
我对这段代码有些困惑:
Timer t = new Timer (1000,new ActionListener() {
private boolean tick = true;
public void actionPerformed (ActionEvent event)
{
if (tick)
// relevant code here continues
我知道我无法从接口实例化对象-我必须从接口创建对象并使用extend
关键字来使用该接口,就像CS蓝图一样。
但是,在行
,new ActionListener() {
// relevant code here continues
尽管看起来可行,但我尚未直接创建实现ActionListener接口的对象。
我正在阅读的书指出:
TimerClass构造函数的第二个参数是一个实现ActionListener接口的对象。此对象是通过匿名类在此处创建的。将ActionListener指定为此类的类型。
但是我看不到我是如何实现的。我以为最初是直接从接口创建对象的,后来发现这是非法的。
该接口如何实现?
解决方法
默认情况下,如果我们考虑匿名类的语法:
new ClassOrInterface() {};
语法需要现有类或接口的名称(要为后者实现)
因此而做
new ActionListener() {// code};
默认情况下,我们已经在实现ActionListener接口。