2

我已经阅读了 Java 中super和的可替代性,因此在超类中合法的相同位置this引用是合法的(除了类 Object 的代码,其中 super 不能出现)。当我对此进行测试时,它似乎失败了,如下例所示:superthis

class OuterSuper {
  public int oneNumber() { return 5; }
  class Inners {}
  int i1 = OuterSuper.this.oneNumber();
  OuterSuper.Inners si1 = OuterSuper.this.new Inners();
}
class Outer extends OuterSuper {
  class Inner {
    int i1 = Outer.this.oneNumber();
    int i2 = Outer.super.oneNumber();
    OuterSuper.Inners si1 = Outer.this.new Inners();
    OuterSuper.Inners si2 = Outer.super.new Inners();
  }
}

编译器对成员 si2 的最后一个声明犹豫不决。在这个例子中,我可以为 int i1 和 i2 编写声明,就像规范所说的那样,我可以将传递给 super 的任何内容替换为超类中的 this。对于内部班级,我被困住了,不得不使用它。这是不一样的吗?我在这两种情况下都在写“Outer.this”和“Outer.super”......

我想分享一下我正在使用 javac(Oracle 1.6 的命令行 JDK)和 NetBeans。我从 javac 得到的错误是:

Exe.java:32: <identifier> expected
        OuterSuper.Inners si2 = Outer.super.new Inners();
                                            ^
Exe.java:32: invalid method declaration; return type required
        OuterSuper.Inners si2 = Outer.super.new Inners();
                                                ^
2 errors
4

3 回答 3

1

So, here are my two-cents. I was under the impression that super could only be used in a class to reference its own base class. I didn't think it was allowed to reference another class' super even given the inner class relationship. This is because no class other that the class itself should be able to bypass method overriding.

So, according to the Java Specification:

It is a compile-time error if the current class is not an inner class of class T or T itself

Given this, your code should compile.

于 2012-11-28T14:27:53.583 回答
0

也许您应该在这两行上使用Outer而不是:OuterSuper

class Outer extends OuterSuper {
  class Inner {
    int i1 = Outer.this.oneNumber();
    int i2 = Outer.super.oneNumber();
    Outer.Inners si1 = Outer.this.new Inners();
    Outer.Inners si2 = Outer.super.new Inners();
  }
}
于 2012-11-28T16:02:53.063 回答
0

类中对 super 的引用等价于超类中对 this 的引用

这种说法是完全不正确的。super.x() 总是指基类的 x() 实现,而超类中的 this.x() 可能指派生类中 x() 的覆盖,如果有的话。

于 2012-11-28T20:54:55.033 回答