Access the Outer attribute of a class from an instance of the Inner class

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 change with my pseudo-code string so that I can compare n values ​​for two instances of the Inner class?

Trying the obvious solution ( n != that.n ) does not compile:

 Outer.java:10: cannot find symbol symbol : variable n location: class Outer.Inner if (n != that.n) // pseudo-code line 
+4
source share
1 answer

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

You can write a getter method in an inner class that returns n outer classes.

Inner Method:

 public int getOuterN() { return n; } 

Then compare using this method:

 getOuterN() != that.getOuterN() 
+7
source

All Articles