faqts : Computers : Programming : Languages : Java

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 4 people (50%) answered Yes
Recently 2 of 4 people (50%) answered Yes

Entry

More than one object can be created for local inner class but not for anonymous inner class? comment

Oct 27th, 2004 22:06
Tom McGuire, Joy Kenneth Harry, http://www.javaworld.com/javaworld/javaqa/2000-03/02-qa-innerclass.html


Such is the nature of "anonymous" inner classes..they are used purely 
as a convenience and I can think of no occasion where one must use them.
Anonymous inner classes are most frequenly used to create a class which 
implements a listener interface. A great example is a UI Component 
which fires an event when the user performs some gesture:
   JButton submit = new JButton("Submit");
   submit.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent ae){
         //your code goes here...
      }
   };
Since the button listener (a callback, really) is tightly coupled to 
the button (submit) there is no compelling reason why you would create 
more than one.
The term "anonymous" refers to the lack of a formal class name and does 
not imply that the object cannot have a named reference. For example:
   JButton submit = new JButton("Submit");
   ActionListener submitListener = new ActionListener(){
      public void actionPerformed(ActionEvent ae){
         //your code here...
      }
   };
   submit.addActionListener(submitListener);
is semantically equivalent to the initial example. This is important to 
realize since there are cases in which listeners must be unregistered 
to prevent memory leaks.
The lack of a formal name does not mean that the class is unnamed--a 
quick look at the compiled .java file will reveal its presence. 
Assuming the above example code was in the file "AIC.java" upon 
compilation you will find 2 class files in your output directory:
AIC.class
AIC$1.class
As far as Java reflection goes, Anonymous Inner Classes are not 
reported when querying a Class for its inner classes.