Anonymous Class在使用外面的local variable的时候,要declare为final,否则会有compiler error.
import javax.swing.JButton; import javax.swing.JTextField; public class HelloWorldAnonymousClasses { public HelloWorldAnonymousClasses() { JButton btnOK = new JButton(); /** * without final, there will be a compilation error. * JTextField jtfContent = new JTextField(); */ final JTextField jtfContent = new JTextField(); btnOK.addActionListener(new java.awt.event.ActionListener(){ public void actionPerformed(java.awt.event.ActionEvent event){ jtfContent.setText("I am OK"); } } ); } public static void main(String... args) { HelloWorldAnonymousClasses hwdc = new HelloWorldAnonymousClasses(); } }
简单地说, JVM为了避免local variable传入anonymous class导致的数据不同步(这个不同步主要和JVM的设计机制相关),要求使用final。
复杂地说: 看这里,非常好的讲解