package timer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.time.Instant; public class TimerTest { public static void main(String[] args) { var listener = new TimePrinter();//构造一个监听器 var timer = new Timer(1000, listener);//一个定时器()中前为计时间隔毫秒,后为传入的对象 timer.start();//启动定时 // keep program running until the user selects "OK" JOptionPane.showMessageDialog(null, "Quit program?"); System.exit(0); } } class TimePrinter implements ActionListener//实现ActionListener接口 { public void actionPerformed(ActionEvent event) { System.out.println("At the tone, the time is " + Instant.ofEpochMilli(event.getWhen()/*会返回这个事件的时间*/)); Toolkit.getDefaultToolkit().beep();//获取工具箱(工具箱中包含GUI环境信息)并发出一声铃响 } }
接口:
在JAVA中一个类可以实现多个接口,但只能有一个超类
接口不能实例化,但可以声明接口变量,且可以使用这个变量引用实现了这个接口的对象
可以同类一样,使用extends扩展接口
接口的所有方法自动为public,且实现接口的那个方法必须声明为public public void actionPerformed(ActionEvent event)
在实现接口时可使用<>为接口提供参数类型 class Employee implements Comparable<Employee>
默认方法:
使用default修饰标记一个方法为默认方法,在接口中。
默认方法与超类冲突时,超类优先;
接口冲突:两个接口方法相同时,只要其中有一个方法是默认方法,便会产生报错;可使用getName方法选择其中一个 public String getName(){return MethodName.super.getName();}