Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-4032110

Inner classes can't access enclosing instance when inner class is subclass of ou

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Won't Fix
    • Icon: P3 P3
    • None
    • 1.1, 1.1.5
    • tools
    • None
    • x86
    • windows_95, windows_nt



      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 - ###@###.###
      ======================================================================

            dstoutamsunw David Stoutamire (Inactive)
            mchamnessunw Mark Chamness (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: