从内部类到lambda表达式
首先讲一讲内部类
内部类是在一个已有的类里面创建一个新的类。
就比如在一个TalkingClock中间创建一个TimePrinter的类,
Time Printer 类我后面会用在 TImer里面当做一个Event。Timer的作用是每过多少毫秒执行一次。
import java.awt.*;
import java.awt.event.*;
import java.time.*;
import javax.swing.*;
public class innerClassTest
{
public static void main(String[] args)
{
TalkingClock clock = new TalkingClock(1000, 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()
{
TimePrinter Listener=new TimePrinter();
Timer timer = new Timer(interval, Listener);
timer.start();
}
public class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.out.println("At the tone, the time is "
+ Instant.ofEpochMilli(event.getWhen()));
if (beep) Toolkit.getDefaultToolkit().beep();
}
}
};
这个报时器会在隔一段时间响一下。
匿名类
我们很容易就能看到TimePrinter只用了一次,呢么我们就可以把这个类匿名
具体方法就是把timePrinter这个类的定义写在赋值语句里面。就如下面的这个代码,唯一需要的就是把接口写在这个赋值语句的最上面。
import java.awt.*;
import java.awt.event.*;
import java.time.*;
import javax.swing.*;
public class innerClassTest
{
public static void main(String[] args)
{
TalkingClock clock = new TalkingClock(1000, 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 ActionListener()
{
System.out.println("At the tone, the time is "
+ Instant.ofEpochMilli(event.getWhen()));
if (beep) Toolkit.getDefaultToolkit().beep();
};
Timer timer = new Timer(interval, Listener);
timer.start();
}
}
最后就是用Lambda表达式
因为Timer()中间使用的是一个时间段(interval)和一个ActionLIstener,所以我们就可以改写这个为Lambda表达式。
import java.awt.*;
import java.awt.event.*;
import java.time.*;
import javax.swing.*;
public class innerClassTest
{
public static void main(String[] args)
{
TalkingClock clock = new TalkingClock(1000, 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 ActionListener()
{
System.out.println("At the tone, the time is "
+ Instant.ofEpochMilli(event.getWhen()));
if (beep) Toolkit.getDefaultToolkit().beep();
};
Timer timer = new Timer(interval,event->
{
System.out.println("At the tone, the time is "
+ Instant.ofEpochMilli(event.getWhen()));
if (beep) Toolkit.getDefaultToolkit().beep();
});
timer.start();
}
}