Search code examples
javainner-classesscjp

What benefit do method-local inner classes provide in Java?


I've just read through the chapter on method-local inner classes in the SCJP book, and I'm really struggling to think of any practical use for them.

I've always been under the impression, that methods should be as small and specific to their task as possible (Orthogonality IIRC), so introducing even the simplest inner class would create heft and unwieldy methods.

Can anyone suggest a good practical usage for method local inner classes? So far it feels as if I might have to understand them purely for passing the exam, and not for use in everyday coding.

Cheers


Solution

  • In most cases (e.g. for action listeners, runnables and such) you would use anonymous classes instead of method-local named classes.

    But there is one thing which named classes can do and anonymous classes can't: implementing more than one interface, or extending a class and interfaces, too. Also, you can create more than one object of this class (without using a loop).