When to use local classes in Java?

Asked

Viewed 75 times

4

I learned that it is possible to declare classes within blocks as methods, for example:

void exemplo() {
    class teste {

    }
}

But when local classes come in handy?

  • Declare class within method I have never seen. Unless it is some new version of Java, I believe it refers to internal classes (Inner classes). But they are not declared within methods but within other classes.

  • @Piovezan Actually this has been around for a long time (see this question 2010, for example). But as it is little used, many people do not even know it is possible (I particularly never use because I never remember...)

  • 1

    @hkotsubo Our :) living and learning.

1 answer

2


It is a matter of scope and visibility. If you have an object defined by that class used it only within this method why other parts of the code should be able to access this class and possibly use it inappropriately, polluting the more general scope (remembering that several tools suggest what can and could suggest this class in some context that cannot use it just because the class has been defined in the more general scope)?

There is a basic rule that you should declare anything in the smallest possible scope that works well, so it improves the legibility encapsulating functionality only where it needs to be used, the more it is visible the more it can give confusion with something else, the code gets less orthogonal.

Some languages prefer to use an anonymous type or tuple to deal with it, because the utility is rarer, if you do it right, if you just need a structure there is not much reason to create a real named and complete type just for this, right?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.