关于内部类的疑惑(新手求助) 下面是一个《Core Java 第一卷》第六中的一个例子,为什么第41行 ActionListener listener = new TimePrinter();可以编译通过,它是怎么编译的? 常规的写法不是ActionListener listener = new ActionListener()吗?
1. import java.awt.*; 2. import java.awt.event.*; 3. import java.util.*; 4. import javax.swing.*; 5. import javax.swing.Timer; 6. 7. public class InnerClassTest 8. { 9. public static void main(String[] args) 10. { 11. TalkingClock clock = new TalkingClock(1000, true); 12. clock.start(); 13. 14. // keep program running until user selects "Ok" 15. JOptionPane.showMessageDialog(null, "Quit program?"); 16. System.exit(0); 17. } 18. } 19. 20. /** 21. A clock that prints the time in regular intervals. 22. */ 23. class TalkingClock 24. { 25. /** 26. Constructs a talking clock 27. @param interval the interval between messages (in milliseconds) 28. @param beep true if the clock should beep 29. */ 30. public TalkingClock(int interval, boolean beep) 31. { 32. this.interval = interval; 33. this.beep = beep; 34. } 35. 36. /** 37. Starts the clock. 38. */ 39. public void start() 40. { 41. ActionListener listener = new TimePrinter(); 42. Timer t = new Timer(interval, listener); 43. t.start(); 44. } 45. 46. private int interval; 47. private boolean beep; 48. 49. private class TimePrinter implements ActionListener 50. { 51. public void actionPerformed(ActionEvent event) 52. { 53. Date now = new Date(); 54. System.out.println("At the tone, the time is " + now); 55. if (beep) Toolkit.getDefaultToolkit().beep(); 56. } 57. } 58. }
------解决方案--------------------
Java code
ActionListener listener = new TimePrinter();
------解决方案--------------------
ActionListener aa = new TimePrinter ();//根据这里就知道TimePrinter 是ActionListener 的子类或者实现(对接口来说)。
父类名 实例名 = new 子类名(); //多态
这是代码了 private class TimePrinter implements ActionListener 50. { 51. public void actionPerformed(ActionEvent event) 52. { 53. Date now = new Date(); 54. System.out.println("At the tone, the time is " + now); 55. if (beep) Toolkit.getDefaultToolkit().beep(); 56. } 57. }
------解决方案--------------------