调用父方法而不是被覆盖的方法

Call parent method instead of the overriden one

我有一个 class C1:

public class C1 {

    public void method() {
      //Do something
    }

    protected void anotherMethod() {
      if (something) {
          method(); 
          /*Here, I want to call the method C1.method, 
           * but C2.method is called
           */
      }
    }

}

还有一个classC2那个extends它和overrides那个method:

public class C2 extends C1 {

    @Override
    public void method() {
        if (something) {
            anotherMethod();
        } else {
            super.method();
        }
    }

}

代码注释中描述了我的问题。我无法在父 class 中 运行 父方法。这是什么原因?

就您的 C2 class 而言,anotherMethod() 未被覆盖,因此如果 something 为真,它会调用自己的 method()

重写如下:

@Override
protected void anotherMethod() {
  if (something) {
      super.method(); //Here, I want to call the method `C1.method`, but `C2.method` is called
  }
}

从子 anotherMethod() 定义中调用父方法。

令人讨厌的是,你不能(抛开反射黑客)。

不过你可以在线上做点什么

public class C1 {
    public final void _method() /*rename to taste*/{
    }

    public void method(){
        _method();
    }
}

并在派生的 class 中覆盖 method。如果您特别需要基本 class 方法,则调用 _method()。我认为这是最接近 C++ 允许的 C1::method() 的写法。