aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Referencing an inner class's outer class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Referencing an inner class Watch "Referencing an inner class New topic
Author

Referencing an inner class's outer class

jean-gobert de coster
Ranch Hand

Joined: Dec 04, 2008
Posts: 49
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

Joined: Aug 03, 2008
Posts: 9304
    
  17

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
jean-gobert de coster
Ranch Hand

Joined: Dec 04, 2008
Posts: 49
So the only solution would then be to implement a getOuter method in my inner class then?
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9304
    
  17

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

Joined: Dec 04, 2008
Posts: 49
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

Joined: Aug 03, 2008
Posts: 9304
    
  17

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...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Referencing an inner class's outer class