• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Referencing an inner class's outer class

 
jean-gobert de coster
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
given an outer class MyOuter with a regular inner class MyInner,

from within one of MyInner's method you could get its outer class by doing MyOuter.this

However I thought that it could then be possible to get an inner class's outer class from outside by doing something like

MyOuter.MyInner inner = new Outer().new Inner();
MyOuter outer = MyOuter.inner;

but this doesn't work. Is there a way, other than implementing a getOuter() method in the inner class, to get its outer class from outside?
 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well jean nice try first of all. I never thought about that syntax. But jean that will not work because the special syntax to access outer class instance is only available to the inner class. It is just a compiler optimization. You can read my blog if you want the complete details. The link is in my signature...
 
jean-gobert de coster
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So the only solution would then be to implement a getOuter method in my inner class then?
 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well I would say Yes, that's the solution. But why do you want to return the outer class instance
 
jean-gobert de coster
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ankit Garg:
well I would say Yes, that's the solution. But why do you want to return the outer class instance


Well I don't have any particular scenario for this, so it's more out of curiosity.

The main reason being: when you instantiate an inner class, you also instantiate its outer class. So what happens to that instance.

Actually, a question comes to mind: how does this all work in terms of GC?

I mean, ok I create an instance of MyOuter and an instance of MyInner, so I have one instance of each on the heap. And on the stack I have my "inner" variable. What prevents the instance of MyOuter from being GC'ed?
 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when you create an instance of an inner class, the outer instance is copied into the inner class. That is why it is not garbage collected...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic