从基类方法调用基类重写函数 [英] 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(字符串)中Bthis的上下文是B的实例。
我可以选择做新的B1()。f1(String) - >(A)f1(String) - >(A)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.
谢谢,
Maxim。
Thank you,
Maxim.
推荐答案
不幸的是,没有
Unfortunately, no
我确定你知道,但我会明确说明为了完整性 - 只有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.method()
- 查找从调用实例的类开始的方法(实例的顶部虚拟表 - 隐含默认值) - super -
super.method()
- 查找从定义调用方法的类的父类开始的方法(调用类'parent'的虚拟表 - 不严格正确,但简化呃想到这种方式 - 谢谢@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)
我可以想象另一个关键词(例如当前?)做你所描述的:
I can imagine another keyword (e.g. current?) do what you describe:
- 当前 -
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屋!