Rule 5: Don’t Use Inner Classes
Some Java language books say that
inner classes can only be accessed by
the outer classes that enclose them.
This is not true. Java byte code has
no concept of inner classes, so inner
classes are translated by the compiler
into ordinary classes that happen to
be accessible to any code in the same
package. And Rule 4 says not to depend
on package scope for protection.
But wait, it gets worse. An inner
class gets access to the fields of the
enclosing outer class, even if these
fields are declared private. And the
inner class is translated into a
separate class. In order to allow this
separate class access to the fields of
the outer class, the compiler silently
changes these fields from private to
package scope! It’s bad enough that
the inner class is exposed, but it’s
even worse that the compiler is
silently overruling your decision to
make some fields private. Don’t use
inner classes if you can help it.
(Ironically, the new Java 2
doPrivileged() API usage guidelines
suggest that you use an inner class to
write privileged code. That’s one
reason we don’t like the
doPrivileged() API.)