jQuery in Action, 3rd edition
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

Win a copy of Introducing JavaFX 8 Programming this week in the JavaFX forum!
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

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

Joined: Sep 20, 2010
Posts: 4086

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

Joined: Oct 13, 2005
Posts: 44433
Agree; anonymous classes are very nice, but you should use them once only. Otherwise it is easier to have an ordinary class.
I agree. Here's the link: http://aspose.com/file-tools
subject: Private inner classes vs. Local inner classes.
It's not a secret anymore!