Java code snippet output explanation required(需要Java代码片段输出说明)
问题描述
我的代码是:
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 中覆盖变量,因此你实际上有两个 a 变量 - 一个在 Foo 和Bar 中的一个.另一方面 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).
但最终您访问 f.a 并且在编译期间使用已知类型的 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 non-final variables in Java should never be public.
这篇关于需要Java代码片段输出说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:需要Java代码片段输出说明
- 如何指定 CORS 的响应标头? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 转换 ldap 日期 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 获取数字的最后一位 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
