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

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

问题描述:



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


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.