Question

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
Was it helpful?

Solution

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()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top