Java Reference
In-Depth Information
An inner class method with the same name as an enclosing class method
hides all overloaded forms of the enclosing class method, even if the in-
ner class itself does not declare those overloaded forms. For example:
class Outer {
void print() { }
void print(int val) { }
class Inner {
void print() { }
void show() {
print();
Outer.this.print();
print(1); // INVALID: no Inner.print(int)
}
}
}
Here the declaration of
Inner.print
hides all forms of
Outer.print
. When
Inner.show
invokes
print(1)
, the compiler reports that
Inner
has no meth-
od
print
that takes an integer argument. The
show
method must ex-
plicitly qualify the method invocation with
Outer.this
. There is a good
reason to do this. Normally, a set of overloaded methods within a class
have the same basic contractthey just operate on different parameter
types. If an inner class method happens to have the same name as an
enclosing class method, there is no reason to assume that it supports
the same contractconsequently, the hiding of the enclosing class's over-
loaded forms prevents a completely unrelated method from being acci-
dentally invoked. As usual, there are few reasons to hide fields or meth-
ods in this way, so the issue is best avoided in the first place. The details
of how method invocations are resolved are discussed in "
Finding the
Right Method
"
on page
224
.