Name: mc57594 Date: 02/12/97
In Java 1.1, an instance of an inner class Inner may access it's
enclosing instance of class Outer by using the syntax
Outer.this
This syntax doesn't work if Inner is a subclass of
Outer. For example:
public class Outer {
int foo() { return 1; }
public class Inner extends Outer {
int foo() { return Outer.this.foo(); }
}
Inner getInner() { return new Inner(); }
public static void main(String[] args) {
Outer x = new Outer();
Outer.Inner y = x.getInner();
System.out.println(y.foo());
}
}
Class Inner is a subclass of Outer, and overrides Outer.foo().
The intent is for Inner.foo() to call the foo() of it's
enclosing instance. However, because Inner is a subclass of
Outer, "Outer.this" is just a synonym for "this." The
result is, instead of calling the enclosing instance's foo()
this.foo() is called: instead of returning the value 1,
the program is caught in an infinite loop.
There are at least two possible solutions to this problem:
a) Never allow an inner class to be a subclass of an outer class.
If you want to achieve the effect desired above, you must write
a top-level subclass of Outer.
b) Provide a keyword, e.g. "enclosing", which is always a
reference to the enclosing instance. In this case, Inner.foo()
could be written as:
int foo() { return enclosing.foo(); }
company - , email - ###@###.###
======================================================================
- relates to
-
JDK-4086803 enclosing class instance method call chokes inner class compile
- Closed