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クラスの2つのインスタンスの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 OO

外側のクラスを返す内側のクラスにgetterメソッドを書くことができますn

上の方法Inner

public int getOuterN() { return n; }

次に、この方法を使用して比較します。

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