匿名阶级难题
我想我了解匿名类的基础知识,但我想澄清一些事情。 当我有这样的语法时
class A
{
class AnonymousClass1 Implements ActionListener{}
}
class A
{
public A()
{
JButton btn = new JButton();
btn.addActionListener( new ActionListener(){} );
}
}
如果匿名类实际上是类 A 的内部类,如第一个示例所示:理论上,语义正确吗?
到底发生了什么?我认为编译java文件时,会为匿名类创建一个.class文件,以便可以引用它(但我找不到它)。当实例化 A 的对象时,它会创建一个按钮对象,然后 btn 调用 addActionListener() 方法,该方法实际上传递类似这样的内容 btn.addActionListener(new AnonymousClassOne())
AnonymousClassOne 是由编译器。
如果不是会发生什么?谢谢。
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(){} );
}
}
If the anonymous class is actually an inner class of class A, as in the first example: in theory, is the semantics right?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
匿名
类可以通过美元符号及其后面的数字来识别 -Class$1.class
。这些课程只是为了您自己的方便。想象一下:这非常乏味。因此,您可以立即使用匿名类创建实现。编译器给出的名称前面有美元符号,后面有一些标识符。
幕后发生的事情是,
Java
创建一个具有自动生成名称的新内部类。如果您发现我的解释混乱,请随时提问。我现在累了。
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: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.
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.
或多或少被编译器重写为
is more or less rewritten by the compiler as