Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner Class vs. Anonymous Inner Class

 
Michael Salvini
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Michael Salvini
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Makes sense, thanks!
 
Aditya Jha
Ranch Hand
Posts: 227
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@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
Posts: 227
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Apologies for the duplicate message. I'm not sure how to delete it.
 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Doesn't matter, I've removed it for you. And yes, that's exactly what I meant.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic