JAVA学习之内部类(三)

时间:2022-10-24 15:31:45
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

public class InnerClassTest
{
public static void main(String[] args)
{
TalkingClock clock = new TalkingClock(10000,true);
clock.start();

JOptionPane.showMessageDialog(null,"Quit program?");
System.exit(0);
}
}

class TalkingClock//TalkingClock类,在该类中定义了一个实现了ActionListener接口的内部类TimerPrinter
{
public TalkingClock(int interval, boolean beep)//TalkingClock的构造函数
{
this.interval = interval;
this.beep = beep;
}
public void start()
{
ActionListener listener = this.new TimePrinter();//在外部类的方法中创建了一个内部类的对象,实现了内部类的引用
Timer t = new Timer(interval, listener);
t.start();
}

private int interval;
private boolean beep;

public class TimePrinter implements ActionListener//实现了ActionListener接口的内部类,并在其中调用了外部类的私有成员beep,访问方式:OuterClass.this.
{
public void actionPerformed(ActionEvent event)
{
Date now = new Date();
System.out.println("At the tone, the time is "+now);
if (TalkingClock.this.beep) Toolkit.getDefaultToolkit().beep();//在内部类中可以访问外部类的成员,包括private的,隐藏了outer.
}
}
}