匿名阶级难题 [英] The Anonymous Class Conundrum

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

问题描述

我想我理解匿名课程的基础知识,但我想澄清一些事情。当我有这样的语法时,

I think I understand the basics of Anonymous classes but I'd like to clarify something. when I have a syntax such as this

class A
{
       class AnonymousClass1 Implements ActionListener{}
}
class A
{
     public A()
     {
        JButton btn = new JButton();

       btn.addActionListener( new ActionListener(){} );
     }
}

如果匿名类实际上是类的内部类A,如第一个例子:理论上,语义是对吗?

If the anonymous class is actually an inner class of class A, as in the first example: in theory, is the semantics right?

究竟发生了什么?我认为在编译java文件时,会为匿名类创建一个.class文件,以便可以引用它(但我找不到它)。当A的对象被实例化时,它会创建一个按钮对象,然后btn调用addActionListener()方法,该方法实际传递类似这样的内容 btn.addActionListener(new AnonymousClassOne()) AnonymousClassOne编译器给出的通用名称。

What happens exactly? I think when the java file is compiled, a .class file is created for the anonymous class so it can be referenced (but I couldn't find it). When an object of A is instantiated it creates a button object, btn then calls the addActionListener() method which actually passes something like this btn.addActionListener(new AnonymousClassOne()) AnonymousClassOne a generic name given by the compiler.

如果没有,会发生什么?谢谢。

If not what happens? Thanks.

推荐答案

匿名类可以通过美元符号识别之后的数字 - Class $ 1.class 。这些课程只是为了您自己的方便。想象一下:

Anonymous classes can be recognized by the dollar sign and a number after it - Class$1.class. These classes are just for your own convenience. Imagine this:

class SaveButtonListener implements ActionListener {
  ...
}

class OpenButtonListener implements ActionListener {
  ...
}

这是很乏味。因此,您可以使用匿名类立即创建实现。编译器在名称前面加上美元符号和一些标识符。

This is very tedious. So you can create the implementation right away with an anonymous class. The compiler gives the name prepending the dollar sign and some identifier after it.

幕后发生的事情是 Java 使用自动生成的名称创建一个新的内部类。

What happens behind the scenes is that Java creates a new inner class with an auto-generated name.

如果您发现我的解释很乱,请随意提问。我现在累了。

Feel free to ask questions if you find my explanation messy. I am tired now.

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

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