In Java, how do I access the outer class when I

2019-01-08 15:19发布

If I have an instance of an inner class, how can I access the outer class from code that is not in the inner class? I know that within the inner class, I can use Outer.this to get the outer class, but I can't find any external way of getting this.

For example:

public class Outer {
  public static void foo(Inner inner) {
    //Question: How could I write the following line without
    //  having to create the getOuter() method?
    System.out.println("The outer class is: " + inner.getOuter());
  }
  public class Inner {
    public Outer getOuter() { return Outer.this; }
  }
}

8条回答
做个烂人
2楼-- · 2019-01-08 15:48

There is no way, by design. If you need to access the outer class through an instance of the inner one, then your design is backwards: the point of inner classes is generally to be used only within the outer class, or through an interface.

查看更多
祖国的老花朵
3楼-- · 2019-01-08 15:55

If you've got a (non-static) inner class, then you're by definition working with something that only functions inside the enclosing context of the outer class. So to get a handle to the inner class, you'd already have to have retrieved it through the outer instance. So the only way I can see to get to the point where you'd need an accessor like that is to have grabbed the inner through the outer ref and then lost or discarded the outer instance reference.

For example:

public class Outer{ 
   public class Inner {
   }
}

public class UsesInner{
 Collection<Outer.Inner> c = new ArrayList<Outer.Inner>();
}

Now the only way you can populate c is by creating Outer() instances. I'd be curious to see a useful purpose for something like this.

查看更多
登录 后发表回答