4

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
0

1 Answer 1

7

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()
Sign up to request clarification or add additional context in comments.

3 Comments

n is a public attribute of Outer, and not accessible as an attribute of that. Trying this gives a "cannot find symbol" error
somebody copied my first answer ;) - does n!= that.n work after all?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.