Java – When to Use Local Classes?

java

I learned about local classes on the Oracle Java Tutorial page. Not nested classes.

I don't see myself using local classes. It makes the code look messy and you can easily do what local classes do with having a class declared separately.

But maybe I'm missing some use cases for it. Are there situations where you would prefer using local classes over other approaches or are local classes just an antiquated feature no one really uses?

Best Answer

Local classes are just a way to encapsulate some state and behavior locally.

But I think you're right; if it's worth doing, it's worth doing in a way that is reusable, and that means public classes, not local ones. Local classes seem to me to be a bit of a code smell because they are indicative of an outer class definition that is too broad; that is, it is being asked to do too much.

Related Topic