I know there are similar question put up related to this issue, but however, I wasn't able to resolve my issue. I've tried to simplify my problem to the following code -
class Outer
{
Outer()
{}
class Inner
{
Inner()
{}
}
void func()
{
System.out.println("Outer");
}
}
public class Nested
{
public static void main(String args[])
{
Outer oo = new Outer();
Outer.Inner ii = oo.new Inner();
// ii.func(); I know this won't work
}
}
Can I call outer class function "func()" from object of inner class "ii"..?? If yes, how?
Short answer: the reference to Outer.this is private in Inner so you cannot access the reference to the Outer instance from an instance of the Inner.
You can export this reference thus:
class Outer {
Outer() {
}
class Inner {
Inner() {
}
public Outer getOuter() {
return Outer.this;
}
}
void func() {
System.out.println("Outer");
}
}
Then you can simply do:
ii.getOuter().func();
Use Outer.this.func() from the inner class. Do note that you can only do this from the inner class, not from outside.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With