Java Inner Classes Are Perverse

[Was 'InnerClassesAreaPerversion.' But this name was UgLy. And perverse.] ...and doesn't fit the conclusion of this page.


JeffGrigg, widely known for his tact and grace ;-> replied to WardsJavaQuestion with...

"Inner classes are a perversion. Why not code blocks or method pointers?"


  1. Having the ability to recursively declare classes within classes (like C++) is a thing of grace, light, and beauty.

  2. Anonymous classes defined from interfaces or other classes are a creative extension.

But
  1. The syntax is somewhat awkward. (But I can't immediately think of a better way of doing it.)

  2. The implementation, with class name mangling, access to 'final' variables, and code generation of accessors is a hack!

  3. The use of AnonymousInnerClasses for event handling is odd, uninspired, and icky.


"Aren't those Sun engineers so incredibly smart and intelligent. They figured out how to add inner classes, including anonymous inner classes, without changing the run time engine at all."

"Right. It's a hack. So they figured out to do dirty tricks with naming tricks and code generation. It's not a refactoring. It's not a design change. It's a hack. And the resulting Java code is UgLy."



Responses:


Because inner classes are more expressive than code blocks and method pointers. The only perversion is their ugly syntax, but they're fundamentally sound and useful.


Inner classes are a perversion of what? They provide a convenient way to limit the scope of one class to another class, which is useful for indicating composite aggregation.


Inner classes aren't great for functors. However, they work great for things like...well, check out how ArrayList or HashMap expose iterators to their contents.

And how is this better than package protected first class classes? (...in the same package as the collection classes, of course.)

Agreed, inner classes are overly verbose as functors. Eclipse will type most of that for you, but it's still more than I want to read.


They are a hack, but a good hack. I don't have to use them, but I do. They make my life easier. I need more good hacks.


EditText of this page (last edited December 2, 2005) or FindPage with title or text search