需要Java代码段输出说明 [英] Java code snippet output explanation required
问题描述
我的代码是:
class Foo {
public int a=3;
public void addFive() {
a+=5;
System.out.print("f ");
}
}
class Bar extends Foo {
public int a=8;
public void addFive() {
this.a += 5;
System.out.print("b ");
}
}
public class TestClass {
public static void main(String[]args) {
Foo f = new Bar();
f.addFive();
System.out.println(f.a);
}
}
输出:
b 3
请向我解释,为什么这个问题的输出是b 3而不是b 13,因为该方法已被覆盖?
Please explain to me, why is the output for this question "b 3" and not "b 13" since the method has been overridden?
推荐答案
你不能在Java中覆盖变量,因此你实际上有两个一个
变量 - 一个在 Foo
中,一个在酒吧
。另一方面 addFive()
方法是多态的,因此它修改了 Bar.a
(调用Bar.addFive()
,尽管静态类型 f
为 Foo
)。
You cannot override variables in Java, hence you actually have two a
variables - one in Foo
and one in Bar
. On the other hand addFive()
method is polymorphic, thus it modifies Bar.a
(Bar.addFive()
is called, despite static type of f
being Foo
).
但是最后你访问 fa
并且使用已知类型的<$ c $在编译期间解析了这个引用c> f ,这是 Foo
。因此从未触及 Foo.a
。
But in the end you access f.a
and this reference is resolved during compilation using known type of f
, which is Foo
. And therefore Foo.a
was never touched.
Java中的BTW非最终变量从不公开。
BTW non-final variables in Java should never be public.
这篇关于需要Java代码段输出说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!