-3

Say I have the follow code:

class Outer {
   int n;
   class Inner {
   }
}

Is it possible for an object of type Inner to access the instance variable n of its Outer object? (When I say its, I mean the Outer object that its associated with.) I understand that within a method of an inner class you can access outer class instance variables and also within the body (for example an instance variable for Inner could initialize to the value of an instnace variable of Outer), but is it possible to more directly access the Outer instance variables? For example, if inner were an object of type Inner, is there anything like inner.n given the code above?

Sorry for the block of text: basically, if inner were an object of type Inner, is there anything like inner.n given the code above?

J. Doe
  • 33
  • 1
  • 5

2 Answers2

2

Sure. Non-static inner-classes are generated in a way that allows them to access any variable in the respective outer-class (which is reason for quite some security-issues). Instances of non-static inner classes can only be generated within a given instance of the outer class and hold a reference to the outer class that allows them access to any variable of the outer class.

For more infos on this topic just read the java language reference.

0

Is it possible for an object of type Inner to access the instance variable n of its Outer object?

Yes, and you can access the fields of other instances of that class as well, even if they are private.

I understand that within a method of an inner class you can access outer class instance variables and also within the body (for example an instance variable for Inner could initialize to the value of an instnace variable of Outer), but is it possible to more directly access the Outer instance variables? For example, if inner were an object of type Inner, is there anything like inner.n given the code above?

You can't access the fields which are visible to the Inner class from another class. Only the inner and out class can access them, unless the fields are public or accessible via normal access modifiers.

basically, if inner were an object of type Inner, is there anything like inner.n given the code above?

Inner doesn't have a field called n so you can't access it using that name even via reflection. What you can do is access Outer.this.n in the inner class, and you can use reflection to get the instance of the Outer class and get it's n field.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130