覆盖方法和字段的不同行为

编程入门 行业动态 更新时间:2024-10-20 21:08:26
本文介绍了覆盖方法和字段的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我刚刚注意到覆盖方法的行为与覆盖字段不同。 考虑以下代码段:

I just noticed that overriding methods does behave different than overriding fields. Considering the following snippet:

public class Bar { int v =1; public void printAll(){ System.out.println(v); printV(); } public void printV(){ System.out.println("v is " + v); } } public class Foo extends Bar { int v = 4; public static void main(String[] args) { Foo foo = new Foo(); foo.printAll(); } public void printV() { System.out.println("The value v is " + v); } }

导致输出结果: 1 值v是4

It result in the output: 1 The value v is 4

因此看起来foo.printV中的方法printV被覆盖,而字段v是没有在酒吧覆盖。有没有人知道这种差异的原因?

So it seems that the method printV in bar is overridden by foo.printV while the field v is not overwritten in bar. Does anyone know a reason for this difference?

谢谢。

推荐答案

我刚刚注意到覆盖方法的行为与覆盖字段不同。

I just noticed that overriding methods does behave different than overriding fields.

没有覆盖领域。您可以 shadow 字段,但不能覆盖它们。字段不是多态的。请参阅 Java语言规范的第6.4.1节了解更多详情。

There's no such thing as "overriding fields". You can shadow fields, but you can't override them. Fields aren't polymorphic. See section 6.4.1 of the Java Language Specification for more details.

请注意,一般情况下,字段始终总是是私有的,这意味着你不会意识到这首先是这个。

Note that in general, fields should almost always be private anyway, which means you wouldn't be aware of this in the first place.

更多推荐

覆盖方法和字段的不同行为

本文发布于:2023-11-15 23:27:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598903.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!