覆盖方法和字段的不同行为 [英] Different behavior of overriding methods and fields

查看:123
本文介绍了覆盖方法和字段的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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


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.

这篇关于覆盖方法和字段的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆