Java – The 4 inner/nested class types

If you are trying to clear your thoughts around just how many different types of inner/nested classes there are in Java, this should be a quick refresher. All but the first kind are known as inner classes.

Static member classes – These will not hold on to a reference to the enclosing class. You do not need a reference to the enclosing class to instantiate this. This one is not really an inner class.

Non static member classes – These will hold on to a reference to the object of the enclosing class. Beware of leaks and concurrency issues. Always make it a static member class if you don’t use anything from the enclosing instance.

Anonymous classes – Good for one off use cases. Can reduce code readability if they get too large. Can be a bit more difficult to unit test.

Local classes – A class that is local to a method/block. Not used too often. Holds a reference to the enclosing instance.



Tags:
This entry was posted on Thursday, January 12th, 2012 at 11:08 pm and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

One Response to “Java – The 4 inner/nested class types”

  1. Aman kinha

    Annonymous simply means nameless.An object that have no reference is known as annonymous object. If you have to use an object only once, annonymous object is a good approach.