Inner classes, also known as nested classes are classes defined within another class.
They may be defined as
or with package access.
They may only be used "in the context" of the containingclass (outer
enclosing class), unless
they are marked as
public(and its containing class is
static, then it can be instantiated without an outer class instance, otherwise, the inner class object must be attached to an instance of the outer class.
Inner classes are used to (these uses overlap to some extent):
privateelements as well as the
privateelements of the outer class object it is attached to
Iteratorinterface to loop through the elements in the collection using
Inner class code has free access to all elements of the outer class object that contains it, by name (no matter what the access level of the elements is).
Outer class code has free access to all elements in any of its inner classes, no matter what their access term.
An inner class compiles to its own class file, separate from that of the
outer class (the name of the file will be
although within your code the name of the class will be
OuterClassName.InnerClassName); you cannot use the dollar sign version of the name in your code.
An inner class occupies its own memory block, separate from the outer class memory block.
An inner class may extend one class, which might be unrelated to the class the outer class extends.
An inner class can implement one of more interfaces, and, if treated as an instance of one of its interfaces, external code may have no knowledge that the object actually comes from an inner class.