Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access outer class function from Object of Inner Class

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?

like image 220
user3554962 Avatar asked Sep 13 '26 23:09

user3554962


2 Answers

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();
like image 58
Boris the Spider Avatar answered Sep 15 '26 11:09

Boris the Spider


Use Outer.this.func() from the inner class. Do note that you can only do this from the inner class, not from outside.

like image 41
Distjubo Avatar answered Sep 15 '26 12:09

Distjubo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!