This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Java in General and the fly likes Private inner classes vs. Local inner classes. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Private inner classes vs. Local inner classes." Watch "Private inner classes vs. Local inner classes." New topic
Author

Private inner classes vs. Local inner classes.

Avor Nadal
Ranch Hand

Joined: Sep 15, 2010
Posts: 122

Hello to you all:

For years I've been using inner classes for certain needs. Specifically private inner classes, because I "return" the public interfaces which they implement instead of themselves. Well, I always used private inner classes for a personal mania of keeping class declarations separated from the method ones.

However, today I've learnt that local inner classes and anonymous inner classes can gain access to the final local variables of the method (something which I only used on JavaScript). With such an advantage I've started to wonder if I should replace the mentioned private classes for these ones, because that way I don't need to pass any reference to the constructor (saving much code), nor declaring any constructor indeed.

What do you opine? I insist about the fact that I'm referring to private inner classes only. Thank you a lot .
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3982
    
  18

Well, if you're only going to use the class in one method, then sure, make it a local class (or even better, an anonymous one, if you only use it once).

I usually do this, unless the class is fairly large. Larger classes will make your code harder to read, if you stick them in a method.


The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
Avor Nadal
Ranch Hand

Joined: Sep 15, 2010
Posts: 122

Stephan van Hulst: Ops, yes, I was referring to classes used once only . Thank you for your opinion.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 43885
    
  32
Agree; anonymous classes are very nice, but you should use them once only. Otherwise it is easier to have an ordinary class.
 
Have you checked out Aspose?
 
subject: Private inner classes vs. Local inner classes.
 
It's not a secret anymore!