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

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

问题描述

在处理匿名内部类时,我对接口的概念感到困惑.据我所知,您无法在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天全站免登陆