简体   繁体   中英

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?

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.

class Outer {
   Outer() {}
   class Inner {
     Inner() {}

     void callFunc() {
       Outer.this.func();
     }
  }

  void func() {
     System.out.println("Nested");
  }
}

public class Nested {
 public static void main(String args[]) {
   Outer.Inner ii = new Outer().new Inner();
   ii.callFunc();

 // ii.func(); I know this won't work
 }
}

This will work for you

package com;


class Outer
{
    Outer()
    {}

    class Inner
    {
        Inner()
        {}
        public Outer g(){
            return Outer.this;}
    }

    void func()
    {
        System.out.println("Outer");
    }
}

public class Test1
{
    public static void main(String args[])
    {
        Outer oo = new Outer();
        Outer.Inner ii = oo.new Inner();


         ii.g().func(); 


    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM