从基类方法调用基类覆盖的函数 [英] Calling base class overridden function from base class method
问题描述
public class A {
public void f1(String str) {
System.out.println("A.f1(String)");
this.f1(1, str);
}
public void f1(int i, String str) {
System.out.println("A.f1(int, String)");
}
}
public class B extends A {
@Override
public void f1(String str) {
System.out.println("B.f1(String)");
super.f1(str);
}
@Override
public void f1(int i, String str) {
System.out.println("B.f1(int, String)");
super.f1(i, str);
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
b.f1("Hello");
}
}
我希望这段代码能输出:
I'm seeking that this code would output:
B.f1(String)
A.f1(String)
A.f1(int, String)
然而我得到:
B.f1(String)
A.f1(String)
B.f1(int, String)
A.f1(int, String)
我知道在 A.f1(String) 中 B 的this"上下文中是 B 的实例.我可以选择执行链 new B1().f1(String) -> (A's) f1(String) -> (A's) f1(int, String) 吗?
I understand that under the context of B "this" in A.f1(String) is B's instance. Do I have the option to do the chain new B1().f1(String) -> (A's) f1(String) -> (A's) f1(int, String) ?
这是一个理论问题,实际上解决方案显然是在 A 中实现 f1(String) 和 f1(int, String) 都会调用的私有函数.
This is a theoretical question, practically the solution would obviously be in A to implement a private function that both f1(String) and f1(int, String) would call.
谢谢,
马克西姆.
Thank you,
Maxim.
推荐答案
很遗憾,没有
我相信你知道,但为了完整性,我会明确说明 - 只有 2 个关键字来控制方法调用:
As i'm sure you're aware, but I'll state explicitly for completeness - there are only the 2 keywords to control the method invocation:
- this -
this.method()
- 从调用实例的类(实例的顶部"虚拟表 - 隐含默认值)开始寻找方法 - super -
super.method()
- 从定义调用方法的类的父类(调用类的父类的虚拟表 - 并非严格正确,但这样想更简单 - 谢谢@maaartinus)
- this -
this.method()
- looks for method starting from the invoking instance's class (the instance's "top" virtual table - implied default) - super -
super.method()
- looks for method starting from the parent class of the class in which the invoking method is defined (the invoking class' parent's virtual table - not strictly true, but simpler to think of this way - thanks @maaartinus)
我可以想象另一个关键字(例如 current?)按照您的描述进行:
I can imagine another keyword (e.g. current?) do what you describe:
- current -
current.method()
- 从定义调用方法的类开始查找方法
- current -
current.method()
- looks for method starting from the class in which the invoking method is defined
但是 Java 没有这样的关键字(还没有?).
but Java doesn't have such a keyword (yet?).
这篇关于从基类方法调用基类覆盖的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!