Anonymous vs named inner classes? – best practices?

One advantage of anonymous inner classes is that no one can ever use it anywhere else, whereas a named inner class can be used (if only by the class that created it if made private). It’s a small distinction, but it does mean that you can protect an inner class from being accidentally used elsewhere.

Also, using the anonymous inner class gives anyone reading your code a head’s up – “this class is being used just here and nowhere else.” If you see a named inner class, someone might think it’d be used in multiple places in the class.

They are very similar, so neither point is a game-changer. I just think it helps for clarity if you use anonymous inner classes for one-offs, and named inner classes when it’s used multiple times within the class.

Leave a Comment