Different behavior of overriding methods and fields

前端 未结 2 1366
误落风尘
误落风尘 2020-12-21 05:09


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

public class Bar {
  int v =1;

         


        
相关标签:
2条回答
  • 2020-12-21 05:51

    When you are calling foo.printAll(); It is calling the function of the base class which is printing the value 1. Then you are calling printV.This time since the inherited class has a function of the same name, it is overridden and printV of Foo is called.

    The value of v depends on from which class you are printing the value.

    0 讨论(0)
  • 2020-12-21 06:03

    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.

    0 讨论(0)
提交回复
热议问题