Java Reference
In-Depth Information
This special syntax is needed only when referring to a member
of a containing class that is hidden by a member of the same
name in the member class.
Scope versus inheritance
We notice that a top-level class can extend a member class. With the introduction
of nonstatic member classes, two separate hierarchies must be considered for any
class. The first is the inheritance hierarchy , from superclass to subclass, that defines
the fields and methods a member class inherits. The second is the containment hier‐
archy , from containing class to contained class, that defines a set of fields and meth‐
ods that are in the scope of (and are therefore accessible to) the member class.
It is important to be familiar with the properties and rules of thumb that the two
hierarchies have:
• The two hierarchies are entirely distinct from each other; it is important that
you do not confuse them.
• Refrain from creating naming conflicts, where a field or method in a superclass
has the same name as a field or method in a containing class.
• If such a naming conflict does arise, the inherited field or method takes prece‐
dence over the field or method of the same name in the containing class.
• Inherited fields and methods are in the scope of the class that inherits them
and take precedence over fields and methods by the same name in enclosing
• To prevent confusion between the class hierarchy and the containment hierar‐
chy, avoid deep containment hierarchies.
• If a class is nested more than two levels deep, it is probably going to cause more
confusion than it is worth.
• If a class has a deep class hierarchy (i.e., it has many ancestors), consider defin‐
ing it as a top-level class rather than as a nonstatic member class.
Local Classes
A local class is declared locally within a block of Java code rather than as a member
of a class. Only classes may be defined locally: interfaces, enumerated types, and
annotation types must be top-level or static member types. Typically, a local class is
defined within a method, but it can also be defined within a static initializer or
instance initializer of a class.
Just as all blocks of Java code appear within class definitions, all local classes are nes‐
ted within containing blocks. For this reason, local classes share many of the
Search WWH ::

Custom Search