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

发布于 2024-08-11 20:13:11 字数 660 浏览 1 评论 0原文

给出以下代码:

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");
//...

我可以用伪代码行交换什么,以便可以比较内部类的两个实例的 n 值?

尝试明显的解决方案 (n != that.n) 无法编译:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

﹉夏雨初晴づ 2024-08-18 20:13:11

与实例方法和变量一样,内部类与其封闭类的实例相关联,并且可以直接访问该对象的方法和字段。 - Java OO

你可以在内部类,返回外部类的n

Inner 上的方法:

public int getOuterN() { return n; }

然后使用此方法进行比较:

getOuterN() != that.getOuterN()

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文