Skip to main content
 首页 » 编程设计

java中Java中使用接口(interface)的匿名内部类

2025年02月15日12myhome

因此,当研究 lambda 表达式并使用它们来替代 Java 中的 EventHandler 的匿名内部类时,我遇到了一些匿名内部类,这让我停下来思考。例如,当为通常实现 ActionListener 的对象编写匿名内部类时,我们会编写

myJButton.addActionListener(new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent e){ 
        //DO SOMETHING 
    } 
}); 

我对此感到困惑的是,ActionListener 是一个接口(interface),所以我认为有必要做一些类似的事情......

myJButton.addActionListener(new myButtonListener implements ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent e){ 
        //DO SOMETHING 
    } 
}); 

但这甚至无法编译。我想我之所以这么认为,显然是因为如果我们使用私有(private)内部类,我们会使用

private MyButtonListener implements ActionListener { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
        //DO SOMETHING 
    } 
} 
myJButton.addActionListener(new MyButtonListener()); 

所以我的问题是:

1) 为什么我们能够直接从接口(interface)创建匿名内部类,而不是通过实现该接口(interface)的类来创建匿名内部类?

2)为什么我无法创建一个实现 ActionListener 的匿名内部类,而不是直接从它创建,如我在第二个代码片段中所示?

请您参考如下方法:

1) Why are we able to create an anonymous inner class directly from an interface rather than having to create one through a class that implements the interface?

2) Why am I unable to create an anonymous inner class that implements ActionListener instead of directly from it as I show in my second code snippet?

当您使用 implements XXXX 创建类时,您正在定义一个类(内部或非内部),并且您必须为其指定一个名称,当然我们可以做到这一点,这就是我们经常做的事情。而匿名内部类没有名字,它更像是一个表达式。


我从 http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html 复制此内容

我认为这将帮助您理解什么是匿名类。

An anonymous class is an expression. They are like local classes except that they do not have a name

。匿名类表达式的语法类似于构造函数的调用,只不过代码块中包含类定义。

考虑 frenchGreeting 对象的实例化:

    HelloWorld frenchGreeting = new HelloWorld() { 
        String name = "tout le monde"; 
        public void greet() { 
            greetSomeone("tout le monde"); 
        } 
        public void greetSomeone(String someone) { 
            name = someone; 
            System.out.println("Salut " + name); 
        } 
    }; 

匿名类表达式由以下部分组成:

  • 新运营商

  • 要实现的接口(interface)或要扩展的类的名称。在此示例中,匿名类正在实现 HelloWorld 接口(interface)。

  • 包含构造函数参数的括号,就像普通的类实例创建表达式一样。注意:当您实现接口(interface)时,没有构造函数,因此您使用一对空括号,如本例所示。

  • 主体,它是类声明主体。更具体地说,在主体中,允许方法声明,但不允许声明。

因为匿名类定义是一个表达式,所以它必须是语句的一部分。在此示例中,匿名类表达式是实例化 frenchGreeting 对象的语句的一部分。 (这解释了为什么右大括号后面有一个分号。)