在Java中看起来像这样:
new JButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // pre that will be performed on any action on this component } };在这里
ActionListener-是一个接口,通过调用
new ActionListener() {};您正在创建匿名类(由于没有名称而被命名为匿名类)-该接口的实现。或者您可以像这样创建内部类:
class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { // pre that will be performed on any action on this component } };然后像这样使用它:
new JButton().addActionListener(new MyActionListener());
此外,您可以将侦听器声明为顶级或静态内部类。但是有时使用匿名内部类非常有用,因为它使您几乎可以在声明侦听器正在监听的组件的位置处实现侦听器。显然,如果侦听器方法代码很长,则不是一个好主意。然后最好将其移动到非匿名内部或静态嵌套或顶级类中。
通常,内部类是非静态类,它们以某种方式驻留在顶级类的主体内。在这里,您可以看到它们在Java中的示例:
//File TopClass.javaclass TopClass { class InnerClass { } static class StaticNestedClass { } interface Fooable { } public void foo() { new Fooable(){}; //anonymous class class LocalClass { } } public static void main(String... args) { new TopClass(); }}


