开发者

Accessing Outer class attribute from an instance of an Inner class

开发者 https://www.devze.com 2022-12-12 17:39 出处:网络
Given the following code: public class Outer { public final int n; public class Inn开发者_运维问答er implements Comparable<Inner>

Given the following code:

public class Outer
{
   public final int n;
   public class Inn开发者_运维问答er 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


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()
0

精彩评论

暂无评论...
验证码 换一张
取 消