package timer;
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;
/**
* 内部类,可以通过反射看出程序中实现的机制
*
* 1.不是每个TalkingClock都有一个TimePrinter实例域,TimePrinter对象是由TalkingClock类的方法构造的
* 2.在TalkingClock类中,编译器加了
* static boolean access$0(TalkingClock);
* 将返回作为参数传递给它的对象域beep - 为内部类访问外部类,增加了特权 - 不安全
* 3.在TimePrinter类中,编译器加了
* public timer.TalkingClock$TimePrinter(TalkingClock);
* final timer.TalkingClock this$0;
* 用于引用外围类(TalkingClock)的对象
*/
public class InnerClassTest {
public static void main(String[] args) {
TalkingClock clock = new TalkingClock(3000, true);
clock.start();
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}
class TalkingClock {
private int interval;
private boolean beep;
public TalkingClock(int interval, boolean beep) {
this.interval = interval;
this.beep = beep;
}
public void start() {
ActionListener listener = new TimePrinter();
Timer timer = new Timer(interval, listener);
timer.start();
}
public class TimePrinter implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
Date now = new Date();
System.out.println("At the tone, the time is : " + now);
/**
* if(beep)
* if(access$0(TalkingClock))
* 等价
*/
if(beep) {
Toolkit.getDefaultToolkit().beep();
}
}
}
}