package innerclass; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; public class InnerClassT { public static void main(String[] args) { } /** * 1.局部内部类 * 类不能用public 或者 private修饰 * * 只有start方法才可以访问 * * 2.外部方法访问变量 * 执行actionPerformed方法的时候,局部变量已经销毁----> * 编译器在内部类构造实例化的时候拷贝一份局部变量 * 局部变量声明为final,保持局部变量和局部类的拷贝保持一致。(若想实现累计可以声明一个数组) * * 3.匿名内部类 * */ class TalkClass{ /* int intervel; boolean beep; public void start(){ class TimePrint implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if (beep) { Toolkit.getDefaultToolkit().beep(); } } } ActionListener listener = new TimePrint(); new Timer(intervel, listener); }*/ public void start(int intervel,final boolean beep){ class TimePrint implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if (beep) { Toolkit.getDefaultToolkit().beep(); } } } ActionListener listener = new TimePrint(); new Timer(intervel, listener); } //匿名内部类 public void startThree(int intervel,final boolean beep){ ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (beep) { Toolkit.getDefaultToolkit().beep(); } } }; new Timer(intervel, listener).start();; } //lambda表达式 可见 labmda表达式必匿名内部类更简洁 public void startFour(int intervel,final boolean beep){ new Timer(intervel, even -> { if (beep) { Toolkit.getDefaultToolkit().beep(); } } ); } } }