views:

141

answers:

1

Given the following code:

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

What can I swap out with my pseudo-code line so that I can compare the values of n for the two instances of the Inner class?

Trying the obvious solution (n != that.n) doesn't compile:

Outer.java:10: cannot find symbol
symbol  : variable n
location: class Outer.Inner
                    if (n != that.n) // pseudo-code line
+3  A: 

As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. - Java OO

You could write a getter method in the inner class, which returns n of the outer class.

Method on Inner:

public int getOuterN() { return n; }

Then compare using this method:

getOuterN() != that.getOuterN()
The MYYN
```n``` is a public attribute of Outer, and not accessible as an attribute of ``that```. Trying this gives a "cannot find symbol" error
rampion
yes, of course. added an alternative using methods ..
The MYYN
somebody copied my first answer ;) - does n!= that.n work after all?
The MYYN
I wound up going with the slightly more general ```public Outer parent() { return Outer.this; }``` so I could access all the members I needed to.
rampion