Java:如何在重写方法(祖父方法)中调用super().super()

Can*_*ner 16 java

可能重复:
为什么是super.super.method(); Java不允许?

我有3个类,他们互相继承如下:

A
 ?
   B
    ?
     C
Run Code Online (Sandbox Code Playgroud)

在每个类中,我有以下方法:

protected void foo() {
    ...
}
Run Code Online (Sandbox Code Playgroud)

课内C我想打电话foo从类A没有调用fooB:

protected void foo() {
    // This doesn't work, I get the following compile time error:
    // Constructor call must be the first statement in a constructor
    super().super().foo(); 
}
Run Code Online (Sandbox Code Playgroud)

编辑
一些上下文信息:
B类是我们使用的实际类.C类是一个单元测试类,它有一些修改.foo里面的方法B做了一些我们不想要的东西,所以我们在里面覆盖它C.但是foo在课堂A上很有用,需要调用.

ass*_*ias 17

  • 要在超类中调用方法,请使用super.foo(),而不是super().foo().super()调用父类的构造函数.
  • 没有办法打电话super.super.foo().您可以super.foo()在B类中添加一个呼叫,这样super.foo()在C中呼叫将super.foo()在B中呼叫,而B又呼叫foo()A.


Rom*_*ain 8

这在Java中是不可能的.你需要依靠B您提供访问到一个明确的方式Afoo.