Anonymous class puzzle

I think I understand the basics of anonymous classes, but I would like to clarify something. when i have syntax like

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 correct?

What exactly is going on? I think that when the java file is compiled, a .class file is created for the anonymous class, so it can be referenced (but I could not find it). When an instance of object A is created, it creates a button object, then btn calls the addActionListener () method, which actually passes something like this btn.addActionListener(new AnonymousClassOne()) AnonymousClassOne is the common name given by the compiler.

If this is not so? Thank.

0
java anonymous-class anonymous-inner-class
Oct. 15 2018-11-11T00:
source share
2 answers

Anonymous classes can be recognized by the dollar sign and the number after it is Class$1.class . These classes are for your convenience only. Imagine the following:

 class SaveButtonListener implements ActionListener { ... } class OpenButtonListener implements ActionListener { ... } 

This is very tiring. This way you can instantly create an implementation with an anonymous class. The compiler gives a name that adds a dollar sign and some identifier after it.

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

Feel free to ask questions if you find my explanation erratic. Now i'm tired.

+2
Oct. 15 2018-11-11T00:
source share
 class A { public A() { JButton btn = new JButton(); btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // ... } }); } } 

more or less rewritten by the compiler as

 class A { private class SomeCuteName implements ActionListener { public void actionPerformed(ActionEvent e) { // ... } } public A() { JButton btn = new JButton(); btn.addActionListener(new SomeCuteName()); } } 
+1
Oct 15 '11 at 18:07
source share



All Articles