从Inner类的实例访问外部类属性

ram*_*ion 4 java nested-class

给出以下代码:

public class Outer
{
   public final int n;
   public class Inner implements Comparable<Inner>
   {
      public int compareTo(Inner that) throws ClassCastException
      {
          if (Outer.this.n != Outer.that.n) // pseudo-code line
          {
               throw new ClassCastException("Only Inners with the same value of n are comparable");
//...
Run Code Online (Sandbox Code Playgroud)

我可以用我的伪代码行替换什么,以便我可以比较Inner类的两个实例的n值?

尝试明显的解决方案(n != that.n)不编译:

Outer.java:10: cannot find symbol
symbol  : variable n
location: class Outer.Inner
                    if (n != that.n) // pseudo-code line
Run Code Online (Sandbox Code Playgroud)

mik*_*iku 7

与实例方法和变量一样,内部类与其封闭类的实例相关联,并且可以直接访问该对象的方法和字段.- Java OO

你可以在内部类中编写一个getter方法,它返回n外部类.

方法Inner:

public int getOuterN() { return n; }
Run Code Online (Sandbox Code Playgroud)

然后使用此方法进行比较:

getOuterN() != that.getOuterN()
Run Code Online (Sandbox Code Playgroud)