Quick Java Question -- How to refer to parent class from inner class?

statik213

Golden Member
Oct 31, 2004
1,654
0
0
Look at the code below:
I'm registerint an anonymous class as an actionlistener for some component. I'd like to be able to refer the instance of the A object that the anonymous actionlistener 'belongs' to (i.e. `this` from A's perspective). I know that I can access any method, field of A but what do I do if I need to pass a reference of A as a paremeter to some other method?
Only way I could think of is in outlined in the second listing below.

 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
Yes, I do believe it is simply the name of the parent class, same syntax as for static variables. I think it would have been clearer if they made another keyword like owner or something, just like this and super but I suppose that would start to get ambiguous when you have multiple levels of nesting :(
 

xtknight

Elite Member
Oct 15, 2004
12,974
0
71
Originally posted by: kamper
Yes, I do believe it is simply the name of the parent class, same syntax as for static variables. I think it would have been clearer if they made another keyword like owner or something, just like this and super but I suppose that would start to get ambiguous when you have multiple levels of nesting :(

If that doesn't work, try a property such as parent. I've never programmed in Java, but I have in Javascript and C++.
 

randumb

Platinum Member
Mar 27, 2003
2,324
0
0
i'm pretty sure inner classes automatically have access to it's container class's instance, so you can do
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
Originally posted by: joshsquall
super? It's a reserved word for referring to the parent class.
Parent as in inheritance, he wants parent as in nesting.
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
Originally posted by: randumb
i'm pretty sure inner classes automatically have access to it's container class's instance, so you can do
Truedat. Unless you have made something with the same name in the inner class, in which case the syntax under discussion is necessary.
 

statik213

Golden Member
Oct 31, 2004
1,654
0
0
Originally posted by: randumb
i'm pretty sure inner classes automatically have access to it's container class's instance, so you can do

The problem came about when I had to pass a reference of the outer class's instance to another method from a method in the inner class. Makes sense?
The syntax: [OuterClassName].this works and I agree a keyword like owner should be there the whole [OuterClassName].this is lengthy and a tad bit confussing.
Also, just to add to this thread, if you need to create an instance of a non-static inner class from outside the owning (outer) class, use:
[OuterClassName].new [InnerClassConstructor]

Thanks all for your help!