首页 > 解决方案 > 从Java中的另一个基类方法调用基类方法而无需反射

问题描述

在 C++ 中,可以显式调用层次结构中特定类的方法。

具体来说,对于派生对象的实例Derived,可以在方法内部时显式调用bar()基类Base(即Base::bar())的Base::foo()方法,即使该bar()方法在派生类中被覆盖。

例如,考虑 C++ 中的这段代码:

struct Base {
  virtual void foo() {
    cout << "Base's foo()" << endl;
    Base::bar(); // <--- This allows to invoke the method of a base class
  }

  virtual void bar() {
    cout << "Base's bar()" << endl;
  }
};

struct Derived: public Base {
  virtual void foo() {
    cout << "Derived's foo()" << endl;
    Base::foo();
  }

  virtual void bar() {
    cout << "Derived's bar()" << endl;
  }
};

对它的调用Derived::foo()如下所示:

Base *p = new Derived();
p->foo();

将导致以下输出:

Derived's foo()
Base's foo()
Base's bar()

这是相当等价的 Java 代码:

class Base {
  public void foo() {
    System.out.println("Base's foo()");
    bar(); // <--- How to invoke the method of a base class here?
  }

  public void bar() {
    System.out.println("Base's bar()");
  }
}

class Derived extends Base {
  @Override
  public void foo() {
    System.out.println("Derived's foo()");
    super.foo();
  }

  @Override
  public void bar() {
    System.out.println("Derived's bar()");
  }
}
Base p = new Derived();
p.foo();

问题是:

标签: javapolymorphismoverridingbase-class

解决方案


推荐阅读