This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
The moose likes Java in General and the fly likes Inner Class vs. Anonymous Inner Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Inner Class vs. Anonymous Inner Class" Watch "Inner Class vs. Anonymous Inner Class" New topic
Author

Inner Class vs. Anonymous Inner Class

Michael Salvini
Greenhorn

Joined: May 25, 2010
Posts: 20
Good Morning All,

I have made it through several Java books and I am reading another one, and started to wonder about something. Some books illustrate the use of an anonymous inner class to do something (in most cases it's an action listener) and some use known inner classes. Two questions come to mind:

1) Which is the better choice and why?

2) Or do they both have uses where one is preferred over the other?

Thanks,
Mike


Learning Java & Studying for the SCJA
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

Anonymous inner class:
Pro: you don't need to make up a class name
Con: you can only use it once

Named inner class:
Pro: you can use it multiple times
Con: you must give it a name

If I need a class only once I always use an anonymous inner class.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Michael Salvini
Greenhorn

Joined: May 25, 2010
Posts: 20
Makes sense, thanks!
Aditya Jha
Ranch Hand

Joined: Aug 25, 2003
Posts: 227

@Rob I suppose when you say 'use the class single/multiple times', you mean 'instantiation can be done single/multiple times'.
Aditya Jha
Ranch Hand

Joined: Aug 25, 2003
Posts: 227

Apologies for the duplicate message. I'm not sure how to delete it.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

Doesn't matter, I've removed it for you. And yes, that's exactly what I meant.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Inner Class vs. Anonymous Inner Class
 
Similar Threads
Do Anonymous Inner Threads use a lot of memory?
Dumb question about how javac names files
anonymous classes
Can we create an inner Class for an INNER CLASS??