Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

private inner class and static private inner class

 
hegde prasanna
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I understand the concept and usage of inner classes in general.
When should we go for a private inner class and when for a static private inner class? I tried searching but it wasn't of much help.
Basically I need to design a caching solution in which I need to timestamp the data object. After timestamping, data will be stored in a HashMap or some other collection. I'm planning to use a wrapper class (which is inner and private) which holds the data object and timestamp. I can make the program work by using either normal inner class or static inner class, however would like to know which is better in such case. Also If I can get some general guidelines as to when to use a staic inner class and when to use a normal inner class, it would help me.

Thanks in advance.



 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd generally advise making it static unless that doesn't do what you need. So the question is, does it need access to instance members of the containing class? If yes, you've got to make it an inner class. If no, there's no reason not to make it a static class.

This is following the principle that you should make things only as accessible as they need to be - the same reason that I'd make methods private if there's no reason not to. An inner class can access more than a static inner class.
 
hegde prasanna
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Matthew. That makes sense to me. I don't need to access anything in the outer class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic