带接口的匿名类 [英] Anonymous class with interface

查看:29
本文介绍了带接口的匿名类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理匿名内部类时,我对接口的概念感到困惑.据我所知,你不能在Java中实例化一个接口,所以下面的语句会出现编译错误

I am confused about the concept of interface when dealing with anonymous inner class. As far as I know that you can't instantiate an interface in Java, so the following statement would have a compile error

     ActionListener action = new ActionListener();  // compile error

当它处理匿名类时会发生什么?为什么它允许使用new?例如:

What happen when it deals with anonymous class? why does it allow to use new? For example:

     JButton button = new JButton("A");
     button.addActionListener(new ActionListener(){    //this is fine
           @Override
           public void actionPerformed(ActionEvent e){

           }
     };

编译器是否只是创建了一个类并在幕后实现了ActionListener?它是如何工作的?

Does the compiler just make a class and implement ActionListener behind the scene? How does it work?

推荐答案

它允许你创建一个新的匿名类来实现 ActionListener 因为你提供了实现,你只是没有给出它是一个类名.

It allows you to create a new anonymous class that implements ActionListener because you're providing the implementation, you're just not giving it a class name.

这篇关于带接口的匿名类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆