java - 从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();
问题是:
- 是否有一种非反射方式来显式调用
Base.bar()
方法Base.foo()
? - 如果这是不可能的,那是什么原因?(阻碍糟糕的设计决策?)
解决方案
推荐阅读
- c# - 将动态创建的用户控件图像和文本高度绑定到网格单元高度 WPF
- c++ - 从 C++ dll 调用 Go dll
- c - 警告:函数“colcheck”的隐式声明 [-Wimplicit-function-declaration]
- html - 最小窗口网页设计
- wordpress - Woocommerce 结帐客户条件
- javascript - 为什么要在 Node js 中使用消息队列?
- python - 如何为 nlp 任务清理 20newsgroup 数据集
- python - 模块化 PyTest
- c - void* 与 char* 具有相同的表示和内存对齐是什么意思?
- python - 如何定义输入为列名的函数?