Different behavior of overriding methods and fields

前端 未结 2 1379
误落风尘
误落风尘 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.

提交回复
热议问题