gontard
gontard

Reputation: 29520

How java implement the access to the enclosing class from an inner inner class?

I have created an inner class in an inner class :

public class EnclosingClass {

    public class InnerClass {
        private EnclosingClass getEnclosing() {
            return EnclosingClass.this;
        }

        public class InnerInnerClass {
            private InnerClass getEnclosing() {
                return InnerClass.this;
            }

            private EnclosingClass getEnclosingOfEnclosing() {
                return EnclosingClass.this;
            }
        }        
    }
}

I have been surprised that java allows the InnerInnerClass to access directly the EnclosingClass. How is this code implemented internally by Java?

The InnerInnerClass keeps two pointers (one on the InnerClass and the other on the EnclosingClass) or the InnerInnerClass access the EnclosingClass through the InnerClass ?

Upvotes: 6

Views: 230

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1500225

You just need to disassemble the resulting class with javap to see what's going on:

private EnclosingClass getEnclosingOfEnclosing();
  Code:
     0: aload_0
     1: getfield      #1                  // Field this$1:LEnclosingClass$InnerClass;
     4: getfield      #3                  // Field EnclosingClass$InnerClass.this$0:LEnclosingClass;
     7: areturn

So first it gets the instance of the directly enclosing class, then it gets the "top-level" enclosing class from that.

Upvotes: 11

Johan
Johan

Reputation: 76547

public and private is a pointer issue, it's a compiler issue.

The question is one of the compiler enforcing the scope of a class/variable/method. Because the private method getEnclosing() falls with the the scope of InnerClass, it can be accessed throughout that class.

Note that pointers have nothing to do with the issue.
Using reflection you can still access private members of a class.

Upvotes: 0

Chris Cooper
Chris Cooper

Reputation: 5122

Unless you make an inner class static, then yes, it does have a reference to the instance it exists within, and can reference it members (including private), the same goes for inner inner classes, inner inner inner classes and so on.

Upvotes: 1

Lee Meador
Lee Meador

Reputation: 12985

If the inner classes are not 'static', they contain references internally to the class in which they are contained.

Upvotes: 1

Related Questions