Java Reference
In-Depth Information
5.2.3. Inheritance, Scoping, and Hiding
Within an inner class, all names declared within the enclosing class are
said to be in scope they can be used as if the inner class code were de-
clared in the outer class. An inner class's own fields and methods (and
nested types) can hide those of the enclosing object. There are two ways
in which this can occur:
a field or method is declared in the inner class
a field or method is inherited by the inner class
In both cases any use of the simple name refers to the member of the
inner class, whether declared or inherited. The enclosing object's field
or method must be accessed explicitly using a qualified- this expression.
In the second case, the use of the simple name can mislead a reader of
the code. Consider the following:
class Host {
int x;
class Helper extends Unknown {
void increment() { x++; } // Not what you think!
}
}
The increment method appears to increment the x field of the enclosing
Host instance. In fact, Unknown also declares a field x and that field is
inherited by Helper . The inherited x field hides the x field from the en-
closing scope, and so it is the inherited x field that is incremented not
the field that is seen in the source code! To avoid giving the reader the
wrong impression about what the code is doing, you should avoid the
use of simple names in this situation. Instead, the reference to x should
be explicitly qualified as either this.x or Host.this.x , depending on which
field it is meant to refer to.
 
Search WWH ::




Custom Search