Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Private inner classes vs. Local inner classes.

 
Avor Nadal
Ranch Hand
Posts: 145
Java Netbeans IDE Postgres Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 5399
52
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Avor Nadal
Ranch Hand
Posts: 145
Java Netbeans IDE Postgres Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan van Hulst: Ops, yes, I was referring to classes used once only . Thank you for your opinion.
 
Campbell Ritchie
Sheriff
Posts: 48415
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agree; anonymous classes are very nice, but you should use them once only. Otherwise it is easier to have an ordinary class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic