Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories


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);
 }
}

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

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?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
319 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...