Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

java - The Anonymous Class Conundrum

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...