简体   繁体   English

从Inner类的实例访问外部类属性

[英]Accessing Outer class attribute from an instance of an 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 swap out with my pseudo-code line so that I can compare the values of n for the two instances of the Inner class? 我可以用我的伪代码行替换什么,以便我可以比较Inner类的两个实例的n值?

Trying the obvious solution ( n != that.n ) doesn't compile: 尝试显而易见的解决方案( n != that.n )无法编译:

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 - Java OO

You could write a getter method in the inner class, which returns n of the outer class. 你可以在内部类中编写一个getter方法,它返回外部类的n

Method on Inner : 方法对Inner

public int getOuterN() { return n; }

Then compare using this method: 然后使用此方法进行比较:

getOuterN() != that.getOuterN()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM