4

给定以下代码:

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");
//...

我可以用我的伪代码行交换什么,以便我可以比较 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
4

1 回答 1

7

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

您可以在内部类中编写一个 getter 方法,该方法返回n外部类。

方法Inner

public int getOuterN() { return n; }

然后使用这种方法进行比较:

getOuterN() != that.getOuterN()
于 2009-11-21T17:31:10.383 回答