JAVA 程序的输出 [多态性,方法覆盖]
Output of JAVA program [polymorphism, method overriding]
我目前正在学习 JAVA 编程语言。在讲师的笔记中,我发现了以下代码片段:
class Base{
void g(){
System.out.print("g-Base ");
}
void f(){
System.out.print("f-Base ");
g();
}
}
class Derived extends Base{
public static void main(String[] args) {
Base b = new Derived(); b.f();
}
void g() {
System.out.print("g-Derived ");
}
void f() {
System.out.print("f-Derived "); super.f();
}
}
问题是:这个程序的输出是什么。我编译并 运行 它并得到: f-Derived f-Base g-Derived
f-Derived 和 f-Base 部分我明白了,但是为什么最后一步打印 "g-Derived",我认为应该是 "g-Base".
让我们跟踪执行顺序:
Derived#f
被调用并打印 `"f-Derived".
Derived#f
然后调用 super.f()
,这意味着 Base#f
.
Base#f
打印 "f-Base"
.
Base#f
然后调用 g()
。由于 g()
在 Derived
中被覆盖,因此调用 Derived#g
。
Derived#g
打印 "g-Derived"
.
编译器知道以下规则:
If a method is called without super
keyword call the Derived
version but if a method is called with super
keyword call the Base
version.
因此,当 super.f()
被调用时, f()
的 Base
版本被调用,但是当 g()
在 Base
版本中被调用时,并且由于这次调用没有 super
关键字(带有隐式 this
关键字,其中 this
指的是 Derived
对象)编译器愉快地调用 Derived
版本,我们得到输出:g-Derived
。希望这会有所帮助。
我目前正在学习 JAVA 编程语言。在讲师的笔记中,我发现了以下代码片段:
class Base{
void g(){
System.out.print("g-Base ");
}
void f(){
System.out.print("f-Base ");
g();
}
}
class Derived extends Base{
public static void main(String[] args) {
Base b = new Derived(); b.f();
}
void g() {
System.out.print("g-Derived ");
}
void f() {
System.out.print("f-Derived "); super.f();
}
}
问题是:这个程序的输出是什么。我编译并 运行 它并得到: f-Derived f-Base g-Derived f-Derived 和 f-Base 部分我明白了,但是为什么最后一步打印 "g-Derived",我认为应该是 "g-Base".
让我们跟踪执行顺序:
Derived#f
被调用并打印 `"f-Derived".Derived#f
然后调用super.f()
,这意味着Base#f
.Base#f
打印"f-Base"
.Base#f
然后调用g()
。由于g()
在Derived
中被覆盖,因此调用Derived#g
。Derived#g
打印"g-Derived"
.
编译器知道以下规则:
If a method is called without
super
keyword call theDerived
version but if a method is called withsuper
keyword call theBase
version.
因此,当 super.f()
被调用时, f()
的 Base
版本被调用,但是当 g()
在 Base
版本中被调用时,并且由于这次调用没有 super
关键字(带有隐式 this
关键字,其中 this
指的是 Derived
对象)编译器愉快地调用 Derived
版本,我们得到输出:g-Derived
。希望这会有所帮助。